基本思路,两个指针都从矩阵左上角出发,一个沿着右上半边移动,一个沿着左下半边移动(碰到边界转向),这样两个指针就压着一条对角线,从而我们只需要打印这个对角线元素,并在每次打印对角线后更新从上到下的标记。
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
Row1, Col1 = 0, 0
Row2, Col2 = 0, 0
endRow, endCol = len(matrix)-1, len(matrix[0])-1
res = []
fromup = False
while Row1 <= endRow:
self.Printlevel(matrix, Row1, Col1, Row2, Col2, fromup, res)
if Col1 == endCol:
Row1 += 1
else:
Col1 += 1
if Row2 == endRow:
Col2 += 1
else:
Row2 += 1
fromup = not fromup
return res
def Printlevel(self, matrix, Row1, Col1, Row2, Col2, fromup, res):
if fromup:
while Row1 <= Row2:
res.append(matrix[Row1][Col1])
Row1 += 1
Col1 -= 1
else:
while Row1 <= Row2:
res.append(matrix[Row2][Col2])
Row2 -= 1
Col2 += 1