您的位置:首页 > 其它

LeetCode-54-Spiral Matrix 模拟

2017-09-19 21:16 423 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: