59. 螺旋矩阵 II

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

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] a = new int[n][n];
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                a[i][j]=0;
            }
        }
        int x=0, y=0, tot=1;
        a[0][0] = 1;
        while(tot < n*n){
            while(y+1<n && a[x][y+1]==0) a[x][++y] = ++tot;
            while(x+1<n && a[x+1][y]==0) a[++x][y] = ++tot;
            while(y-1>=0 && a[x][y-1]==0) a[x][--y] = ++tot;
            while(x-1>=0 && a[x-1][y]==0) a[--x][y] = ++tot;
        }
        return a;
    }
}
原文地址:https://www.cnblogs.com/Roni-i/p/10527688.html