这道题看到很多解法都是边界法。然后看到另外一种有意思的解法。
用一个队列,储存四种 行为,即 event,这个行为不合法之后,循环下一个行为,直到行为的开始也不合法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| from typing import Optional, List
from ListNode import ListNode
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]: toDoList = [[0, 1], [1, 0], [0, -1], [-1, 0]] result = [] x = 0 y = 0 m = len(matrix) n = len(matrix[0]) errorNum = 101
result.append(matrix[x][y]) matrix[x][y] = errorNum temp = toDoList.pop(0) toDoList.append(temp) toDoX = temp[0] toDOY = temp[1]
while True: if not ((x + toDoX < m) and (y + toDOY < n) and (matrix[x + toDoX][y + toDOY] != errorNum)): temp = toDoList.pop(0) toDoList.append(temp) toDoX = temp[0] toDOY = temp[1] if not ((x + toDoX < m) and (y + toDOY < n) and (matrix[x + toDoX][y + toDOY] != errorNum)): break else: x += toDoX y += toDOY result.append(matrix[x][y]) matrix[x][y] = errorNum
return result
if __name__ == '__main__': solution = Solution() matric = [[1]] print(solution.spiralOrder(matric))
|