59. 螺旋矩阵 II

题目描述

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

示例 1:

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

输入:n = 1
输出:[[1]]

提示:

1 <= n <= 20


做题思路

这个题目是我第三次刷了吧好像,每次做都有不一样的思考

大体的方向还是通过顺时针遍历去求解,但是有一点就是这次我做的时候发现

返回的答案每次如果n为奇数的情况下,中间那个值都是0

所以我就在结尾做了一个判断如果 ((n&1)==1) 则res[n/2] [n/2]=n*n

虽然做了好几遍了,但这次做的时候还是把这个条件给漏掉了,没有考虑完整。

代码实现

class Solution {
    public int[][] generateMatrix(int n) {
      int[][] res=new int[n][n];
      int count=1;
      
      int left=0;
      int right=n-1;
      int button=0;
      int top=n-1;
      while(left<right && button<top){

        for(int i=left;i<right;i++){
          res[button][i]=count;
          count++;
        }

        for(int i=button;i<top;i++){
          res[i][right]=count;
          count++;
        }

        if(button!=top){
          for(int i=right;i>left;i--){
            res[top][i]=count;
            count++;
          }
        }

        if(right!=left){
          for(int i=top;i>button;i--){
            res[i][left]=count;
            count++;
          }
        }

        left++;
        right--;
        button++;
        top--;
      }
      if((n&1)==1){
        res[n/2][n/2]=n*n;
      }
      return res;
    }
}
// 1   2  3   4 
// 12 13  14  5
// 11 16  15  6
// 10  9  8   7

题目链接

59. 螺旋矩阵 II

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C_x_330

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值