Problem

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Solution

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if (n == 0) return res;
        int num = 1, rStart = 0, rEnd = n-1, cStart = 0, cEnd = n-1;
        while (rStart <= rEnd && cStart <= cEnd) {
            for (int j = cStart; j <= cEnd; j++) res[rStart][j] = num++;
            rStart++;
            for (int i = rStart; i <= rEnd; i++) res[i][cEnd] = num++;
            cEnd--;
            for (int j = cEnd; j >= cStart; j--) {
                if (rStart > rEnd) break;
                res[rEnd][j] = num++;
            }
            rEnd--;
            for (int i = rEnd; i >= rStart; i--) {
                if (cStart > cEnd) break;
                res[i][cStart] = num++;
            } 
            cStart++;
        }
        return res;
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论