[LC] 59. Spiral Matrix II


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 ]
]

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int beginRow = 0, endRow = n - 1;
        int beginCol = 0, endCol = n - 1;
        int num = 1;
        while(beginRow <= endRow && beginCol <= endCol) {
            for(int i = beginCol; i <= endCol; i++) {
                matrix[beginRow][i] = num;
                num += 1;
            }
            beginRow += 1;
            
            for (int i = beginRow; i <= endRow; i++) {
                matrix[i][endCol] = num;
                num += 1;
            }
            endCol -= 1;
            // no need to check boarder b/c it is square
            for (int i = endCol; i >= beginCol; i--) {
                matrix[endRow][i] = num;
                num += 1;
            }
            endRow -= 1;
            
            for (int i = endRow; i >= beginRow; i--) {
                matrix[i][beginCol] = num;
                num += 1;
            }
            beginCol += 1;
        }
        return matrix;
    }
}

 



posted @ 2020-01-02 06:15  xuan_abc  阅读(157)  评论(0)    收藏  举报