0
点赞
收藏
分享

微信扫一扫

LeetCode练习4:螺旋矩阵II

小安子啊 2022-03-12 阅读 71

LeetCode链接:力扣

题目:

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

示例一:

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

 代码:

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int startx = 0, starty = 0;
        int loop = n/2;             //每个圈循环几次,向上取整
        int mid = n / 2;
        int count = 1;              //给途径的位置赋值
        int offset = 1;             //控制每条边遍历的长度
        int i, j;
        while(loop-- != 0){
            i = startx;
            j = starty;

            //从左到右,左闭右开
            for(j = starty; j < starty + n - offset; ++j){
                res[startx][j] = count++;
            }

            //从上到下,左闭右开
            for(i = startx; i < startx + n - offset; ++i){
                res[i][j] = count++;
            }

            //从右到左,左闭右开
            for(; j > starty; --j){
                res[i][j] = count++;
            }

            //从下到上,左闭右开
            for(; i > startx; --i){
                res[i][j] = count++;
            }

            //第二圈开始,起始位置各自加1
            startx++;
            starty++;

            offset += 2;
        }

        //如果n为奇数,需要给中间位置单独赋值
        if(n % 2 != 0){
            res[mid][mid] = count;
        }
        return res;

    }
}
举报

相关推荐

0 条评论