首页 > 试题广场 >

对角线遍历矩阵

[编程题]对角线遍历矩阵
  • 热度指数:1220 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个大小为 n*m 的矩阵,请以对角线遍历并返回遍历结果

数据范围: ,矩阵中的元素满足
示例1

输入

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

输出

[1,2,4,7,5,3,6,8,9]
示例2

输入

[[1,3],[2,4]]

输出

[1,3,2,4]
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param mat int整型二维数组
# @return int整型一维数组
#
class Solution:
    def diagonalOrder(self, mat: List[List[int]]) -> List[int]:
        # write code here
        if len(mat) == 0:
            return []
        up_and_right = 1
        x = 0
        y = 0
        res = []
        while not (x == len(mat) - 1 and y == len(mat[0]) - 1):
            res.append(mat[x][y])
            if up_and_right:
                if x - 1 = len(mat[0]):
                    up_and_right = False
                    # 右上部分顺时针寻找
                    if y + 1 < len(mat[0]):
                        y += 1
                        continue
                    if x + 1 < len(mat):
                        x += 1
                        continue
                else:
                    x -= 1
                    y += 1
            else:
                if x + 1 >= len(mat) or y - 1 < 0:
                    up_and_right = True
                    # 左下部分逆时针寻找
                    if x + 1 < len(mat):
                        x += 1
                        continue
                    if y + 1 < len(mat[0]):
                        y += 1
                        continue
                else:
                    x += 1
                    y -= 1
        res.append(mat[x][y])
        return res
发表于 2024-04-27 00:33:16 回复(0)