Skip to content
文档章节

54 旋转矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

题解

记录访问过的位置存放在 visited 中,顺时针访问,遇到边界或者遇到访问过的位置,就改变方向。

1. 时间复杂度:O(mn)

2. 空间复杂度:O(mn)

py
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
      m = len(matrix)
      n = len(matrix[0])

      visited = [[0 for x in range(n)] for x in range(m)]
      answer = []

      i = 0
      j = 0
      direction = 'right'
      while i >= 0 and i < m and j >= 0 and j < n:

        if visited[i][j] == 1:
          break

        answer.append(matrix[i][j])
        visited[i][j] = 1

        # 计算下一个位置
        if direction == "right":
          # 更换方向
          if j == n-1 or visited[i][j + 1] == 1:
            direction = 'down'
            # 此时 i 是否安全?
            i += 1
          else:
            j += 1

        elif direction == "left":
          if j == 0 or visited[i][j -1] == 1:
            direction = "up"
            i -= 1
          else:
            j -= 1
        elif direction == "up":
          if i == 0 or visited[i-1][j] == 1:
            direction = 'right'
            j += 1
          else:
            i -= 1
        elif direction == "down":
          if i == m -1 or visited[i+1][j] == 1:
            direction = "left"
            j -= 1
          else:
            i += 1

      return answer

同样的解法,看看官方解法代码简洁

py
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()

        rows, columns = len(matrix), len(matrix[0])
        visited = [[False] * columns for _ in range(rows)]
        total = rows * columns
        order = [0] * total

        directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        row, column = 0, 0
        directionIndex = 0
        for i in range(total):
            order[i] = matrix[row][column]
            visited[row][column] = True
            nextRow, nextColumn = row + directions[directionIndex][0], column + directions[directionIndex][1]
            if not (0 <= nextRow < rows and 0 <= nextColumn < columns and not visited[nextRow][nextColumn]):
                directionIndex = (directionIndex + 1) % 4
            row += directions[directionIndex][0]
            column += directions[directionIndex][1]
        return order

作者:力扣官方题解
链接:https://leetcode.cn/problems/spiral-matrix/solutions/275393/luo-xuan-ju-zhen-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

解法二:分层 先外层访问,后内容访问,查看官方代码

py
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()

        rows, columns = len(matrix), len(matrix[0])
        order = list()
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                order.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                order.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left, -1):
                    order.append(matrix[bottom][column])
                for row in range(bottom, top, -1):
                    order.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return order

作者:力扣官方题解
链接:https://leetcode.cn/problems/spiral-matrix/solutions/275393/luo-xuan-ju-zhen-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
``