class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# 用四个数对应4个遍历的方向[0, 1, 2, 3] - [右,下,左,上]
go_state = 0 # 起始必须向右
# record_matrix = [[0] * n for _ in range(m)]
n_0, n_1, n_2, n_3 = 0, 0, 0, 0
m, n = len(matrix), len(matrix[0])
go_num, limit_num = 0, len(matrix) * len(matrix[0])
ans = []
i, j = 0, 0
while go_num < limit_num :
ans.append(matrix[i][j])
# record_matrix[i][j] = 1
go_num += 1
if go_state == 0:
if j == n - 1 - n_1:
go_state = 1
i += 1
n_0 += 1
else:
j += 1
elif go_state == 1:
if i == m - 1 - n_2:
go_state = 2
j -= 1
n_1 += 1
else:
i += 1
elif go_state == 2:
if j == n_3:
go_state = 3
i -= 1
n_2 += 1
else:
j -= 1
else:
if i == n_1:
go_state = 0
j += 1
n_3 += 1
else:
i -= 1
return ans
个人解法:
1.用4个状态标记遍历的走向
2.当前状态的结束状态依赖于下一个状态的完全执行次数
3.用遍历的元素数量作为退出循环的临界
大佬们的解法:
这种解法和大佬的方法二思路一致,其方法一则将当前状态以及该状态下对当前坐标的动作融合起来了,可以参考:https://leetcode.cn/problems/spiral-matrix/solutions/2966229/liang-chong-fang-fa-jian-ji-gao-xiao-pyt-4wzk