59. 螺旋矩阵 II

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

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii

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

原文地址:https://www.cnblogs.com/xxxsans/p/13789652.html