思路:用set记录走过的地方,记下走的方向,根据方向碰壁变换
class Solution:
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
max_rows = len(matrix)
max_cols = len(matrix[0])
block_nums = max_cols * max_rows
count = 1
i = 0
j = 0
answer = [matrix[0][0]]
direction = 'right'
visited_block={(0,0)}
while count < block_nums:
#print(i, j, count, answer, direction)
#print(matrix)
if direction == 'right':
if j < max_cols - 1 and (i,j+1) not in visited_block:
j = j + 1
answer.append(matrix[i][j])
visited_block.add((i,j))
count += 1
continue
else:
direction = 'down'
if direction == 'down':
if i < max_rows - 1 and (i+1,j) not in visited_block:
i += 1
answer.append(matrix[i][j])
visited_block.add((i, j))
count += 1
continue
else:
direction = 'left'
if direction == 'left':
if j > 0 and (i,j-1) not in visited_block:
j -= 1
answer.append(matrix[i][j])
visited_block.add((i, j))
count += 1
continue
else:
direction = 'up'
if direction == 'up':
if i > 0 and (i-1,j) not in visited_block:
i -= 1
answer.append(matrix[i][j])
visited_block.add((i, j))
count += 1
continue
else:
direction = 'right'
#print(answer)
return answer