leetcode-498:对角线遍历

简介: 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]

解题

方法一:对角线迭代和翻转

矩形的形状为N*M,对角线的数量有N+M-1个。当第d条对角线是偶数(d)时候,反一下对角线的顺序。

class Solution:
    def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
        # Check for empty matrices
        if not matrix or not matrix[0]:
            return []
        # Variables to track the size of the matrix
        N, M = len(matrix), len(matrix[0])
        # The two arrays as explained in the algorithm
        result, intermediate = [], []
        # We have to go over all the elements in the first
        # row and the last column to cover all possible diagonals
        for d in range(N + M - 1):
            # Clear the intermediate array everytime we start
            # to process another diagonal
            intermediate.clear()
            # We need to figure out the "head" of this diagonal
            # The elements in the first row and the last column
            # are the respective heads.
            r, c = 0 if d < M else d - M + 1, d if d < M else M - 1
            # Iterate until one of the indices goes out of scope
            # Take note of the index math to go down the diagonal
            while r < N and c > -1:
                intermediate.append(matrix[r][c])
                r += 1
                c -= 1
            # Reverse even numbered diagonals. The
            # article says we have to reverse odd 
            # numbered articles but here, the numbering
            # is starting from 0 :P
            if d % 2 == 0:
                result.extend(intermediate[::-1])
            else:
                result.extend(intermediate)
        return result
相关文章
|
4月前
leetcode94二叉树的中序遍历(迭代做法)
leetcode94二叉树的中序遍历(迭代做法)
20 0
|
4月前
leetcode-590:N 叉树的后序遍历
leetcode-590:N 叉树的后序遍历
25 0
|
4月前
leetcode-589:N 叉树的前序遍历
leetcode-589:N 叉树的前序遍历
16 0
leetcode-589:N 叉树的前序遍历
|
4月前
|
算法 Java C++
leetcode-145:二叉树的后序遍历
leetcode-145:二叉树的后序遍历
25 0
|
4月前
|
索引
leetcode106从中序与后序遍历序列构造二叉树刷题打卡
leetcode106从中序与后序遍历序列构造二叉树刷题打卡
21 0
|
4月前
|
C++ Python
leetcode-94:二叉树的中序遍历
leetcode-94:二叉树的中序遍历
24 0
|
4月前
|
Java C++ 索引
leetcode-106:从中序与后序遍历序列构造二叉树
leetcode-106:从中序与后序遍历序列构造二叉树
27 0
|
4月前
|
Java C++ Python
leetcode-144:二叉树的前序遍历
leetcode-144:二叉树的前序遍历
30 0
|
2天前
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
6 0
|
2天前
|
算法
leetcode代码记录(二叉树递归遍历
leetcode代码记录(二叉树递归遍历
6 0

热门文章

最新文章