-
解题思路:宏观思路,一圈一圈打,确定好「一圈」的左上角以及右下角,然后再打印。有两种特殊情况,左上角和右上角的列相等时,只需要打一行即可;左上角的列和右下角的列相等时,只需打印一列即可。
-
代码:
from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: n = len(matrix) m = len(matrix[0]) ans = [] begin_r = 0 begin_c = 0 end_r = n - 1 end_c = m - 1 while begin_r <= end_r and begin_c <= end_c: # 一圈一圈打印 if begin_r == end_r: # 只需要打印一行 tmp = begin_c while tmp <= end_c: ans.append(matrix[begin_r][tmp]) tmp += 1 break if begin_c == end_c: # 只需打印一列 tmp = begin_r while tmp <= end_r: ans.append(matrix[tmp][end_c]) tmp += 1 break # 上 tmp = begin_c while tmp <= end_c: ans.append(matrix[begin_r][tmp]) tmp += 1 # 右 tmp = begin_r + 1 while tmp <= end_r: ans.append(matrix[tmp][end_c]) tmp += 1 # 下 tmp = end_c - 1 while tmp >= begin_c: ans.append(matrix[end_r][tmp]) tmp -= 1 # 左 tmp = end_r - 1 while tmp > begin_r: ans.append(matrix[tmp][begin_c]) tmp -= 1 # 打印完一圈后,更新左上角点 和右下角点 begin_r += 1 begin_c += 1 end_r -= 1 end_c -=1 return ans