码迷,mamicode.com
首页 > 其他好文 > 详细

498. Diagonal Traverse 对角线遍历矩阵

时间:2018-02-06 01:22:20      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:inpu   lin   xpl   image   out   技术分享   body   turn   www   

 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






498. Diagonal Traverse 对角线遍历矩阵

标签:inpu   lin   xpl   image   out   技术分享   body   turn   www   

原文地址:https://www.cnblogs.com/xiejunzhao/p/8419850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!