Leetcode 54. 螺旋矩阵
题目说明
给定一个包含 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]
题目解析
-
常规做法
建立路径数组,走过记1,没走过记0,方向数组 (0,1)(1,0)(0,-1)(-1,0),螺旋加入结果数组,当个数等于数组长度时,返回结果数组。
-
python zip 旋转法
Python代码
- 常规做法
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row, col, result, di, px, py = len(matrix), len(matrix[0]), [], 0, 0, -1
sign = [[0] * col for i in range(row)]
go = ((0, 1), (1, 0), (0, -1), (-1, 0))
while len(result) < row * col:
x, y = go[di][0], go[di][1]
while 0 <= px + x < row and 0 <= py + y < col and not sign[px + x][py + y]:
px, py = px + x, py + y
result.append(matrix[px][py])
sign[px][py] = 1
di = (di + 1) % 4
return result
- python zip 旋转法
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
while matrix:
res += matrix.pop(0)
matrix = list(zip(*matrix))[::-1]
return res