Skip to content

Commit

Permalink
螺旋矩阵
Browse files Browse the repository at this point in the history
  • Loading branch information
rinwf committed Sep 22, 2018
1 parent def2f0d commit b6d32a2
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions lc54. Spiral Matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return matrix
res = []
direcs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
d = 0
pos = [0, 0]
N = len(matrix)
M = len(matrix[0])
left, right = -1, M
top, button = -1, N
size = M * N
for i in range(size):
# print(pos[0], pos[1])
res.append(matrix[pos[0]][pos[1]])
if pos[1] + direcs[d][1] == right:
d = (d + 1) % 4
top += 1
elif pos[1] + direcs[d][1] == left:
d = (d + 1) % 4
button -= 1
elif pos[0] + direcs[d][0] == button:
d = (d + 1) % 4
right -= 1
elif pos[0] + direcs[d][0] == top:
d = (d + 1) % 4
left += 1

pos[0] += direcs[d][0]
pos[1] += direcs[d][1]
return res


nums = [
]
s = Solution()
print(s.spiralOrder(nums))

0 comments on commit b6d32a2

Please sign in to comment.