1. 程式人生 > >498. Diagonal Traverse 對角線遍歷矩陣

498. Diagonal Traverse 對角線遍歷矩陣

bsp 筆記 body nat solution itl put [] ted

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:

  1. The total number of elements of the given matrix will not exceed 10,000.

  1. class Solution:
  2. def findDiagonalOrder(self, matrix):
  3. """
  4. :type matrix: List[List[int]]
  5. :rtype: List[int]
  6. """
  7. if not matrix or not matrix[0]:
  8. return []
  9. res = []
  10. isRe = 1
  11. def addLine(row, col, isRe):
  12. line = []
  13. while
    row < len(matrix) and col >= 0:
  14. line.append(matrix[row][col])
  15. row += 1
  16. col -= 1
  17. l = len(res)
  18. if isRe:
  19. res[l:l] = line[::-1]
  20. else:
  21. res[l:l] = line
  22. for i in range(len(matrix[0])):
  23. addLine
    (0, i, isRe)
  24. isRe ^= 1
  25. for i in range(1, len(matrix)):
  26. addLine(i, len(matrix[i]) - 1, isRe)
  27. isRe ^= 1
  28. return res




來自為知筆記(Wiz)

498. Diagonal Traverse 對角線遍歷矩陣