题目
给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
示例:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1, 2, 4, 7, 5, 3, 6, 8, 9]
解释:
说明:
给定矩阵中的元素总数不会超过 100000 。
解答一
def findDiagonalOrder(matrix: [[int]]) -> [int]:
m, n = len(matrix), len(matrix[0])
up = True # 移动方向, 是否往上移动
x, y = 0, 0 # 初始坐标
ret = [matrix[0][0]]
for _ in range(m * n - 1):
if up:
x -= 1
y += 1
# 判断是否同时越界
if x < 0 and y >= n:
x = 1
y = n - 1
up = not up
# 判断x是否越界
if x < 0:
x = 0
up = not up
# 判断y是否越界
if y >= n:
up = not up
x += 2
y = n - 1
else:
x += 1
y -= 1
# 判断是否同时越界
if y < 0 and x >= m:
y = 1
x = m - 1
up = not up
# 判断x是否越界
if x >= m:
up = not up
y += 2
x = m - 1
# 判断y是否越界
if y < 0:
y = 0
up = not up
ret.append(matrix[x][y])
return ret
逻辑都是遍历的死逻辑,需要注意的是,在同时越界的时候的处理。
地址
https://leetcode-cn.com/explore/featured/card/array-and-string/199/introduction-to-2d-array/774/