leetcode讲解之螺旋矩阵

  一、题目内容

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

  示例 1:

  


  输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]

  输出:[1,2,3,6,9,8,7,4,5]

  示例 2:

  


  输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

  输出:[1,2,3,4,8,12,11,10,9,5,6,7]

  提示:

  m == matrix.length

  n == matrix[i].length

  1 <= m, n <= 10

  -100 <= matrix[i][j] <= 100

  二、解题思路

  确定上下左右的边界,然后按照螺旋的顺序进行存储,每完成一个方向的存储,就让边界进行加1或减1的变化;

  如果左右或者上下边界重合,则说明遍历完毕;

  三、代码

  class Solution:

  def spiralOrder(self, matrix: list) -> list:

  if len(matrix) == 0 or len(matrix[0]) == 0:

  return []

  res = []

  up = 0

  down = len(matrix) - 1

  left = 0

  right = len(matrix[0]) - 1

  while 1:

  for i in range(left, right + 1):

  res.append(matrix[up][i])

  up += 1

  if up > down:

  break

  for i in range(up, down + 1):

  res.append(matrix[i][right])

  right -= 1

  if right < left:

  break大连人流医院 http://www.dlbybyw.com/

  for i in range(right, left - 1, -1):

  res.append(matrix[down][i])

  down -= 1

  if down < up:

  break

  for i in range(down, up - 1, -1):

  res.append(matrix[i][left])

  left += 1

  if left > right:

  break

  return res

  if __name__ == '__main__':

  s = Solution()

  matrix = [[1, 2, 3, 4],

  [5, 6, 7, 8],

  [9, 10, 11, 12]

  ]

  ans = s.spiralOrder(matrix)

  print(ans)

(完)