思路:用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_rowscount = 1i = 0j = 0answer = [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 + 1answer.append(matrix[i][j])visited_block.add((i,j))count += 1continueelse:direction = 'down'if direction == 'down':if i < max_rows - 1 and (i+1,j) not in visited_block:i += 1answer.append(matrix[i][j])visited_block.add((i, j))count += 1continueelse:direction = 'left'if direction == 'left':if j > 0 and (i,j-1) not in visited_block:j -= 1answer.append(matrix[i][j])visited_block.add((i, j))count += 1continueelse:direction = 'up'if direction == 'up':if i > 0 and (i-1,j) not in visited_block:i -= 1answer.append(matrix[i][j])visited_block.add((i, j))count += 1continueelse:direction = 'right'#print(answer)return answer