leetcode_498. 对角线遍历

给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。

 

示例:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

输出:  [1,2,4,7,5,3,6,8,9]

解释:

 

说明:

给定矩阵中的元素总数不会超过 100000 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diagonal-traverse
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
    def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return []
        rows=len(matrix)#行
        columns=len(matrix[0])#列
        res=[]
        t=[]
        #先按列添加对角线以上
        direction=1
        for i in range(columns):
            t.clear()
            r=0
            c=i
            while r<rows and c>-1:
                t.append(matrix[r][c])
                r+=1
                c-=1
            if direction==1:
                res.extend(t[::-1])
            else:
                res.extend(t)
            direction*=-1
        #再按行添加对角线下
        for i in range(1,rows):
            t.clear()
            r=i
            c=columns-1
            while r<rows and c>-1:
                t.append(matrix[r][c])
                r+=1
                c-=1
            if direction==1:
                res.extend(t[::-1])
            else:
                res.extend(t)
            direction*=-1
        
        return res
            
原文地址:https://www.cnblogs.com/hqzxwm/p/14410101.html