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:

  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






posted @ 2018-02-05 23:19  xiejunzhao  阅读(459)  评论(0编辑  收藏  举报