LeetCode59. 螺旋矩阵 II

版权声明: https://blog.csdn.net/weixin_40550726/article/details/82533337

给定一个正整数 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 startCol=0;
        int startRow=0;
        int endRow=res.length-1;
        int endCol=res[0].length-1;
        for(int count=1;count<=n*n;){

            //top
            for (int j=startCol;j<=endCol;j++){
               res[startRow][j]=count;
               count++;
            }
            startRow++;

            //right
            for (int i=startRow;i<=endRow;i++){
               res[i][endCol]=count;
               count++;
            }
            endCol--;

            //down
            for (int j=endCol;j>=startCol;j--){
                res[endRow][j]=count;
                count++;
            }
            endRow--;

            //left
            for (int i=endRow;i>=startRow;i--){
                res[i][startCol]=count;
                count++;
            }
            startCol++;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40550726/article/details/82533337