498. Diagonal Traverse 對角線遍歷矩陣
阿新 • • 發佈:2018-02-06
bsp 筆記 body nat solution itl put [] ted
來自為知筆記(Wiz)
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 = 1
def addLine(row, col, isRe):
line = []
while
row < len(matrix) and col >= 0:line.append(matrix[row][col])
row += 1
col -= 1
l = len(res)
if isRe:
res[l:l] = line[::-1]
else:
res[l:l] = line
for i in range(len(matrix[0])):
addLine
(0, i, isRe)isRe ^= 1
for i in range(1, len(matrix)):
addLine(i, len(matrix[i]) - 1, isRe)
isRe ^= 1
return res
來自為知筆記(Wiz)
498. Diagonal Traverse 對角線遍歷矩陣