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 。

  • 分析:

仔细观察输出的结果,发现对角线上的值,在二维数组中对应的 row+line 值都是相同的,故通过该规律得到一个按遍历顺序输出的 list,接着需要将 list中为奇数的值所在的line,按倒序输出结果,即可得到按对角线输出的结果

  • 解法:

class Solution(object):
    def findDiagonalOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
		res = []
        lines = collections.defaultdict(list)
        for row in range(len(matrix)):
            for line in range(len(matrix[0])):
                lines[row+line].append(matrix[row][line])
        for key, value in lines.items():
            if key % 2 == 0:
                res += value[::-1]
            else:
                res += value
        return res
posted @ 2019-05-03 19:16  AimeeGao  阅读(201)  评论(0编辑  收藏  举报