0054. 螺旋矩阵 #55
Replies: 4 comments 1 reply
-
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
while matrix:
res += matrix.pop(0)
if not matrix:
break
matrix = self.turnMatrix(matrix)
return res
def turnMatrix(self, matrix: List[List[int]]) -> List[int]:
rows = len(matrix)
cols = len(matrix[0])
newmat = []
for i in range(cols):
newrow = []
for j in range(rows):
newrow.append(matrix[j][i])
newmat.append(newrow)
newmat.reverse()
return newmat |
Beta Was this translation helpful? Give feedback.
-
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ans = []
x, y = 0, 0
dx, dy = 0, 1
nx, ny = 0, 0
m = len(matrix)
n = len(matrix[0])
up, down, left, right = 0, m-1, 0, n-1
while True:
if nx < up or nx > down or ny < left or ny > right:
if nx < up:
left += 1
if left > right:
break
elif nx > down:
right -= 1
if right < left:
break
elif ny < left:
down -= 1
if down < up:
break
elif ny > right:
up += 1
if up > down:
break
dx, dy = dy, -dx
x, y = x + dx, y + dy
else:
x, y = nx, ny
ans.append(matrix[x][y])
nx, ny = x+dx, y+dy
return ans |
Beta Was this translation helpful? Give feedback.
-
|
你好!思路里面的第二点中的叙述应为“按照顺时针的顺序”,你写成逆时针了。 |
Beta Was this translation helpful? Give feedback.
-
|
class Solution: 要理解 range(right, left-1, -1) 中的 left-1,核心是先掌握 Python range() 函数的本质规则,再结合 “从右到左遍历” 的需求来拆解 ——left-1 是为了让遍历 “刚好覆盖到 left 这个目标列”。 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
0054. 螺旋矩阵 | 算法通关手册
https://algo.itcharge.cn/solutions/0001-0099/spiral-matrix/
Beta Was this translation helpful? Give feedback.
All reactions