(Leetcode) 对角线遍历 - Python实现

题目:

给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

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

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

-------------------------------------------------------------

思路:

这里其实主要设计两个方向的判定问题,一个方向是往右上方↗移动,另一个方向是往左下方↙移动。

右上方移动的边界条件:上边界到顶x=0,右边界到头y=n

左下方移动的边界条件:下边界到底x=m,左边界到投y=0

解法1:从头开始遍历每个元素,碰到边界条件就转向

class Solution(object):
    def findDiagonalOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        m = len(matrix)
        if not m:
            return []
        n = len(matrix[0])
        if not n:
            return []
        matrix_num = m*n

        count = 0
        x = y = 0
        li = []
        direction = "up"
        while count < matrix_num:
            count += 1
            li.append(matrix[x][y])
            # 右上方向
            if direction == "up":
                # 无需调换方向的条件(1.x>0 碰到上壁前, 2.y<n-1碰到右壁前)
                if x > 0 and y < n-1:
                     x -= 1
                     y += 1
                     continue
                else:
                    direction = "down"
                    # 碰到上壁 x=0
                    if x == 0 and y < n-1:
                        y += 1
                    # 碰到右壁
                    elif y == n-1:
                        x += 1
            # 左下方向
            else:
                # 无需调换方向的条件(1.x<m 碰到下壁前, 2.y>0 碰到右壁前)
                if x < m-1 and y > 0:
                    x += 1
                    y -= 1
                    continue
                else:
                    direction = "up"
                    if x == m-1:
                        y += 1
                    elif y == 0 and x < m-1:
                        x += 1
        return li

参考:

https://blog.csdn.net/qq_32424059/article/details/88355539

https://blog.csdn.net/huhehaotechangsha/article/details/86527230

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值