给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
输入:
[
[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]:
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
retv = []
i, j = 0, 0
right, down, left, up = 1, 0, 0, 0
for _ in range(m*n):
retv.append(matrix[i][j])
matrix[i][j] = 0
if right:
if j + 1 == n or matrix[i][j + 1] == 0:
right, down = 0, 1
i += 1
else:
j += 1
elif down:
if i + 1 == m or matrix[i + 1][j] == 0:
down, left = 0, 1
j -= 1
else:
i += 1
elif left:
if j - 1 < 0 or matrix[i][j - 1] == 0:
left, up = 0, 1
i -= 1
else:
j -= 1
elif up:
if i - 1 < 0 or matrix[i - 1][j] == 0:
up, right = 0, 1
j += 1
else:
i -= 1
return retv
评论区里面的解答同样是改方向,但是非常简洁,贴过来参考,他用di和dj两个变量控制方向,很巧妙。具体含义可以观察:
向右: d i = 0 , d j = 1 di = 0, dj = 1 di=0,dj=1
向下: d i = 1 , d j = 0 di = 1, dj = 0 di=1,dj=0
向左: d i = 0 , d j = − 1 di = 0, dj = -1 di=0,dj=−1
向上: d i = − 1 , d j = 0 di = -1, dj = 0 di=−1,dj=0
可以观察到,每次转方向的时候都是 d i , d j = d j , − d i di, dj = dj, -di di,dj=dj,−di
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
r, i, j, di, dj = [], 0, 0, 0, 1
if matrix != []:
for _ in range(len(matrix) * len(matrix[0])):
r.append(matrix[i][j])
matrix[i][j] = 0
if matrix[(i + di) % len(matrix)][(j + dj) % len(matrix[0])] == 0:
di, dj = dj, -di
i += di
j += dj
return r