498. Diagonal Traverse 对角线遍历矩阵
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.
Example:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Explanation:
Note:
- The total number of elements of the given matrix will not exceed 10,000.
class Solution:def findDiagonalOrder(self, matrix):""":type matrix: List[List[int]]:rtype: List[int]"""if not matrix or not matrix[0]:return []res = []isRe = 1def addLine(row, col, isRe):line = []while row < len(matrix) and col >= 0:line.append(matrix[row][col])row += 1col -= 1l = len(res)if isRe:res[l:l] = line[::-1]else:res[l:l] = linefor i in range(len(matrix[0])):addLine(0, i, isRe)isRe ^= 1for i in range(1, len(matrix)):addLine(i, len(matrix[i]) - 1, isRe)isRe ^= 1return res


浙公网安备 33010602011771号