59.螺旋矩阵II(Spiral Matrix II)

59.螺旋矩阵(Spiral Matrix)

题解

有了54.螺旋矩阵的基础,解决本题轻而易举。可回顾54.螺旋矩阵CSDN或者54.螺旋矩阵LeetCode

碰壁转向

碰到边界,就转向!
显而易见,填写数字方向顺序是固定的:右,下,左,上
我们利用结果数组 r e s res res中已填写的数字和给定的矩阵的范围来构造边界

  1. 定义最终结果 r e s res res n ∗ n n*n nn的矩阵,全部初始化为 F a l s e False False,表示未填充数字。

  2. 定义方向列表 d i r e c t i o n s = [ [ 0 , 1 ] , [ 1 , 0 ] , [ 0 , − 1 ] , [ − 1 , 0 ] ] directions=[[0,1],[1,0],[0,-1],[-1,0]] directions=[[0,1],[1,0],[0,1],[1,0]],分别对应右,下,左,上。定义当前访问行列索引 x = 0 x=0 x=0, y = 0 y=0 y=0。定义方向计数器 c o u n t = 0 count=0 count=0

  3. 需要填写 n ∗ n n*n nn次,因此需要遍历 n ∗ n n*n nn次,遍历范围 [ 1 , n ∗ n ] [1,n*n] [1,nn]

    • r e s [ x ] [ y ] res[x][y] res[x][y]等于 i i i。表示已经填入数字。
    • 取出当前方向 d i r _ x = d i r e c t i o n s [ c o u n t ] [ 0 ] , d i r _ y = d i r e c t i o n s [ c o u n t ] [ 1 ] dir\_x=directions[count][0],dir\_y=directions[count][1] dir_x=directions[count][0],dir_y=directions[count][1],判断下一步是否越界:
      • 越界条件由三部分组成: 0 < = x + d i r _ x < n 0<=x+dir\_x<n 0<=x+dir_x<n表示行在矩阵范围内, 0 < = y + d i r _ y < n 0<=y+dir\_y<n 0<=y+dir_y<n表示列在矩阵范围内, r e s [ x + d i r x ] [ y + d i r y ] res[x+dir_x][y+dir_y] res[x+dirx][y+diry] F a l s e False False表示下一步填写位置还未填写,即没有碰到边界。若同时满足,说明下一词填写没有越界,则更新 x , y x,y x,y x + = d i r _ x , y + = d i r _ y x+=dir\_x,y+=dir\_y x+=dir_xy+=dir_y
      • 若不满足边界条件,说明碰壁了,需要换方向,更新方向计数器 c o u n t = ( c o u n t + 1 ) % 4 count=(count+1)\%4 count=(count+1)%4变换方向后是一定不会碰壁的 ,从而更新 x , y x,y x,y x = x + d i r e c t i o n s [ c o u n t ] [ 0 ] x=x+directions[count][0] x=x+directions[count][0] y = y + d i r e c t i o n s [ c o u n t ] [ 1 ] y=y+directions[count][1] y=y+directions[count][1]
  4. 返回 r e s res res

复杂度分析

  • 时间复杂度: O ( n 2 ) O\left(n^{2}\right) O(n2),因为遍历一次矩阵。
  • 空间复杂度: O ( n 2 ) O\left(n^{2}\right) O(n2)

Python

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        res=[[False]*n for _ in range(n)]
        directions=[[0,1],[1,0],[0,-1],[-1,0]]
        x,y=0,0
        count=0
        
        for i in range(1,n*n+1):
            res[x][y]=i
            dir_x,dir_y=directions[count][0],directions[count][1]
            if(0<=x+dir_x<n and 0<=y+dir_y<n and not res[x+dir_x][y+dir_y]):
                x=x+dir_x
                y=y+dir_y
            else:
                count=(count+1)%4
                x=x+directions[count][0]
                y=y+directions[count][1]
        return res
         

Java(待完成)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值