Python3求解旋转矩阵问题
原题 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]
解题:
class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:m = len(matrix)if m == 0:return []n = len(matrix[0])if n == 0:return 0res = []dir = 1 # 方向:1 右 2 下 3 左 4 上x = 0 # 起始列标y = 0 # 起始行标while True:if x == -1 or x == n or y == -1 or y == m or matrix[y][x] == None:breakres.append(matrix[y][x])matrix[y][x] = Noneif dir == 1 and ( x + 1 == n or matrix[y][x + 1] == None):dir = 2elif dir == 2 and (y + 1 == m or matrix[y + 1][x] == None):dir = 3elif dir == 3 and (x - 1 == -1 or matrix[y][x - 1] == None):dir = 4elif dir == 4 and (y - 1 == -1 or matrix[y - 1][x] == None):dir = 1if dir == 1:x += 1elif dir == 2:y += 1elif dir == 3:x -= 1elif dir == 4:y -= 1return res