给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3

输出:

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


class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int count = 1, left = 0, right = n - 1, top = 0, bot = n - 1;
        while(count <= n*n) {
            for(int col = left; col <= right; col++)
                res[top][col] = count++;
            top++;
            if(count <= n*n) {
                for(int row = top; row <= bot; row++)
                    res[row][right] = count++;
                right--;
            }
            if(count <= n*n) {
                for(int col = right; col >= left; col--)
                    res[bot][col] = count++;
                bot--;
            }
            if(count <= n*n) {
                for(int row = bot; row >= top; row--)
                    res[row][left] = count++;
                left++;
            }
        }
        return res;
    }
}

LeetCode 原题传送门

Q.E.D.


知识的价值不在于占有,而在于使用