[LeetCode]螺旋矩阵 II

很经典的题目,以前看ACM的书的时候对这道题目印象颇深。

问题链接:https://leetcode-cn.com/problems/spiral-matrix-ii/

代码:

    public int[][] generateMatrix(int n) {
        int[][] array = new int[n][n];
        int i = 0;
        int j = -1;
        int count = 1;
        while(count<=n*n){
            while(j+1 < n&&array[i][j+1]==0) array[i][++j] = count++;
            while(i+1 < n&&array[i+1][j]==0) array[++i][j] = count++;
            while(j-1 >= 0&&array[i][j-1]==0) array[i][--j] = count++;
            while(i-1 >= 0&&array[i-1][j]==0) array[--i][j] = count++;
        }
        return array;
    }

猜你喜欢

转载自blog.csdn.net/sinat_37273780/article/details/84960429