LeetCode 59. Spiral Matrix II 螺旋矩阵II(Java)

题目:

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

解答:

本题与LeetCode 54. Spiral Matrix 螺旋矩阵思路基本相同。
通过四个边界标志位 top、down、left、right 来标记矩阵的四个边界,然后分别沿四个方向依次写入对应值,并不断缩短边界

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int num = 1;
        int top = 0;
        int left = 0;
        int right = n-1;
        int down = n-1;
        while(num <= n*n) {
            for(int i=left; i<=right; i++) {
                res[top][i] = num++;
            }
            top++;
            for(int i=top; i<=down; i++) {
                res[i][right] = num++;
            }
            right--;
            for(int i=right; i>=left; i--) {
                res[down][i] = num++;
            }
            down--;
            for(int i= down; i>=top; i--) {
                res[i][left] = num++;
            }
            left++;
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode)