螺旋矩阵【数组】

本文介绍了一种名为螺旋矩阵的问题的解决方案,通过模拟实现螺旋遍历二维矩阵并计算了时间复杂度和空间复杂度,均为O(nm)。代码中定义了一个Solution类的spiralOrder方法,用于生成螺旋顺序的整数列表。
摘要由CSDN通过智能技术生成

Problem: 54. 螺旋矩阵

思路 & 解题方法

简单模拟

复杂度

时间复杂度:

添加时间复杂度, 示例: O ( n m ) O(nm) O(nm)

空间复杂度:

添加空间复杂度, 示例: O ( n m ) O(nm) O(nm)

Code

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        m, n = len(matrix), len(matrix[0])
        note = [[False] * n for i in range(m)]
        # to:1右 2下 3左 4上
        to = 1
        count = m * n
        r, l = 0, 0
        ans = []
        while count > 0:
            if to == 1:
                while l < n and not note[r][l]:
                    ans.append(matrix[r][l])
                    note[r][l] = True
                    l += 1
                    count -=1
                l -= 1
                r += 1
                to = 2
            elif to == 2:
                while r < m and not note[r][l]:
                    ans.append(matrix[r][l])
                    note[r][l] = True
                    r += 1
                    count -= 1
                r -= 1
                l -= 1
                to = 3
            elif to == 3:
                while l >= 0 and not note[r][l]:
                    ans.append(matrix[r][l])
                    note[r][l] = True
                    l -= 1
                    count -= 1
                l += 1
                r -= 1
                to = 4
            else:
                while r >= 0 and not note[r][l]:
                    ans.append(matrix[r][l])
                    note[r][l] = True
                    r -= 1
                    count -= 1
                r += 1
                l += 1
                to = 1
            print(note)
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Alan_Lowe

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

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

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

打赏作者

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

抵扣说明:

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

余额充值