深色模式
498 对角线遍历.md
题目参考 对角线遍历
分析
触顶反弹,方向改变,注意在定点处特殊处理
题解
py
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m = len(mat) # y 方向
n = len(mat[0]) # x 方向
direction = 'up'
i = 0 # y 方向
j = 0 # x 方向
answer = []
while i < m or n < n:
answer.append(mat[i][j])
if i == m-1 and j == n -1:
break
# 向上到顶,换方向
elif i == 0 and direction == 'up':
direction = 'down'
# 判断右上角处理
if j == n -1:
i += 1
else:
j += 1
# 向上右边到顶换方向
elif j == n -1 and direction == "up":
i += 1
direction = 'down'
# 向下左边到顶
elif j == 0 and direction == "down":
direction = 'up'
# 处理左下角
if i == m -1:
j += 1
else:
i += 1
elif i == m -1 and direction == 'down':
direction = 'up'
j += 1
elif direction == 'up':
i -= 1
j += 1
elif direction == 'down':
i += 1
j -= 1
return answer