题目描述:
dj思路:
这题主要在于上下边界的处理,假设上下左右四个边界为
left, right, up, down = 0, n-1, 0, n-1
step1:
从左边界遍历到右边界,依次记录元素;
遍历结束之后,上边界 up += 1;
判断up是否大于down,大于退出循环
step2:
从上边界遍历到下边界,依次记录元素;
遍历结束之后,右边界 right -= 1;
判断left是否大于right,大于就退出循环
然后,是右边界到左边界的遍历,下边界到上边界的遍历,直到边界冲突,退出循环
代码:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# 行数
row = len(matrix)
# 列数
clo = len(matrix[0])
left, right, up, down = 0, clo - 1, 0, row - 1
res = []
t = True
while t:
for i in range(left, right+1):
res.append(matrix[up][i])
up += 1
if up > down: break
for j in range(up, down+1):
res.append(matrix[j][right])
right -= 1
if right < left: break
for i in range(right, left-1, -1):
res.append(matrix[down][i])
down -= 1
if up > down: break
for j in range(down, up-1, -1):
res.append(matrix[j][left])
left += 1
if left > right: break
return res