螺旋矩阵

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

示例:

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

#思路

定义left,right,top,down为四个边界。

left = 0,right = n - 1, top = 0, down = n - 1;

每当移动到边界时,需要改变边界条件。

比如当向右移动到边界时,应向下继续移动,则top需要向下移一位。

for(int i = l; i  <= r;i++) res[t][i] =  count++; t ++;

while循环控制条件 count <=target

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int[][] generateMatrix(int n) {
         int l = 0, r = n - 1, t = 0, d = n - 1;
        int[][] res = new int[n][n];
         
        int target = n*n;
        int count = 1;
        while(count <= target){
            for(int i = l; i<= r;i++) {  res[t][i] = count++;}
            t++;
            for(int i = t; i <= d;i++) { res[i][r] = count++; }
            r--;
            for(int i = r; i >= l;i--) { res[d][i] = count++;}
            d--;
            for(int i = d; i >= t;i--) { res[i][l] = count++;}
            l++;
        }
        return res;
    }
}

  

posted @   NOE42  阅读(200)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示