zoukankan      html  css  js  c++  java
  • 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
                
    
  • 相关阅读:
    【模板】多项式开根(加强版)
    【模板】多项式幂函数 (加强版)
    Codeforces Round #628 (Div. 2) 总结
    [TJOI2017] 不勤劳的图书管理员
    [HNOI2015] 接水果
    [USACO3.4] Raucous Rockers
    [CF1268B] Domino for Young
    Linux提权小结
    weblogic漏洞练习
    SSL/TLS 安全测试
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14410101.html
Copyright © 2011-2022 走看看