题目:
给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
示例:
输入:
[[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]]
输出: [1,2,4,7,5,3,6,8,9]
说明: 给定矩阵中的元素总数不会超过 100000 。
-------------------------------------------------------------
思路:
这里其实主要设计两个方向的判定问题,一个方向是往右上方↗移动,另一个方向是往左下方↙移动。
右上方移动的边界条件:上边界到顶x=0,右边界到头y=n
左下方移动的边界条件:下边界到底x=m,左边界到投y=0
解法1:从头开始遍历每个元素,碰到边界条件就转向
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
m = len(matrix)
if not m:
return []
n = len(matrix[0])
if not n:
return []
matrix_num = m*n
count = 0
x = y = 0
li = []
direction = "up"
while count < matrix_num:
count += 1
li.append(matrix[x][y])
# 右上方向
if direction == "up":
# 无需调换方向的条件(1.x>0 碰到上壁前, 2.y<n-1碰到右壁前)
if x > 0 and y < n-1:
x -= 1
y += 1
continue
else:
direction = "down"
# 碰到上壁 x=0
if x == 0 and y < n-1:
y += 1
# 碰到右壁
elif y == n-1:
x += 1
# 左下方向
else:
# 无需调换方向的条件(1.x<m 碰到下壁前, 2.y>0 碰到右壁前)
if x < m-1 and y > 0:
x += 1
y -= 1
continue
else:
direction = "up"
if x == m-1:
y += 1
elif y == 0 and x < m-1:
x += 1
return li
参考:
https://blog.csdn.net/qq_32424059/article/details/88355539
https://blog.csdn.net/huhehaotechangsha/article/details/86527230