class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
d=[[0,1],[1,0],[0,-1],[-1,0]]
Lenm=len(matrix)
if Lenm==0:return []
if Lenm==1:return matrix[0]
Lenn=len(matrix[0])
used=[[0 for x in range(Lenn)]for y in range(Lenm)]
x=0
y=0
direction=0
ans=[matrix[0][0]]
used[0][0]=1
for i in range(1,Lenm*Lenn):
while(True):
newx=x+d[direction][0]
newy=y+d[direction][1]
if newx>=0 and newx<Lenm and newy>=0 and newy<Lenn and used[newx][newy]==0:
used[newx][newy]=1
ans.append(matrix[newx][newy])
x=newx
y=newy
break
else:
direction=(direction+1)%4
return ans
本文介绍了一种螺旋遍历二维矩阵的算法实现。通过定义方向数组来控制遍历路径,确保了遍历过程覆盖矩阵中所有元素且不重复。适用于需要按螺旋顺序访问二维数组的应用场景。

147

被折叠的 条评论
为什么被折叠?



