螺旋矩阵【数组】

Problem: 54. 螺旋矩阵

文章目录

  • 思路 & 解题方法
  • 复杂度
  • Code

思路 & 解题方法

简单模拟

复杂度

时间复杂度:

添加时间复杂度, 示例: 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

你可能感兴趣的:(研一开始刷LeetCode,矩阵)