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
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
相关文章推荐
- LeetCode-54-Spiral Matrix(矩阵/模拟/递归)-Medium
- LeetCode 54 Spiral Matrix (模拟 蛇形填数)
- leetcode 54 54. Spiral Matrix(矩阵顺时针绕圈输出)
- 【leetcode】【54】Spiral Matrix
- Leetcode 54, Spiral Matrix
- 【LeetCode】(54)Spiral Matrix(Medium)
- Leetcode 54. Spiral Matrix (Medium) (java)
- 【LeetCode】C# 54、Spiral Matrix
- leetCode 54.Spiral Matrix(螺旋矩阵) 解题思路和方法
- LeetCode 54 Spiral Matrix
- leetcode54 Spiral Matrix
- leetcode[54]Spiral Matrix
- LeetCode 54 Spiral Matrix
- [C语言][LeetCode][54]Spiral Matrix
- Leetcode 54 Spiral Matrix
- LeetCode 54/59. Spiral Matrix i, ii
- [leetcode]54. Spiral Matrix(Java)
- [leetcode54] Spiral Matrix
- LeetCode 54. Spiral Matrix(螺旋矩阵Ⅰ)
- LeetCode(54)(59) Spiral Matrix I II