【leetcode刷题】20T23-螺旋矩阵

  • 2020 年 2 月 26 日
  • 筆記

木又同学2020年第23篇解题报告

leetcode第54题:螺旋矩阵

https://leetcode-cn.com/problems/spiral-matrix/


【题目】

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

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

【思路】

使用up、down、left、right来控制上下左右四个边界,然后,开始循环吧,跟着我上一行、右一列、下一行、左一列,好,再来一次……

【代码】

python版本

class Solution(object):      def spiralOrder(self, matrix):          """          :type matrix: List[List[int]]          :rtype: List[int]          """          if len(matrix) == 0 or len(matrix[0]) == 0:              return []          up, down = 0, len(matrix) - 1          left, right = 0, len(matrix[0]) - 1          res = []          i, j = 0, 0            while up <= i <= down and left <= j <= right:              # 上方一行              for j in range(left, right + 1):                  res.append(matrix[i][j])              up += 1              if up > down:                  break              # 右方一列              j = right              for i in range(up, down + 1):                  res.append(matrix[i][j])              right -= 1              if left > right:                  break              # 下方一行              i = down              for j in range(right, left - 1, -1):                  res.append(matrix[i][j])              down -= 1              if up > down:                  break              # 左方一列              j = left              for i in range(down, up - 1, -1):                  res.append(matrix[i][j])              left += 1              if left > right:                  break              i = up              j = left          return res