Spiral Matrix

川长思鸟来 2021-12-17 10:43 257阅读 0赞

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

  1. [
  2. [ 1, 2, 3 ],
  3. [ 4, 5, 6 ],
  4. [ 7, 8, 9 ]
  5. ]

You should return [1,2,3,6,9,8,7,4,5].

剑指offer的题目.很有意思,但是非常考验细节的题目,主体细节在circle这个函数,每次走四个方向.从左朝右,从上朝下,从右朝左,从下朝上.和剑指offer的思路不一样.我没有加过多判断.而是要求每次按行按列走都要走完,走完之后,修改index,将该行或者该列删除.复杂度O(m*n),代码如下:

  1. class Solution(object):
  2. def spiralOrder(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. m = len(matrix)
  11. n = len(matrix[0])
  12. xBegin = 0
  13. xEnd = m - 1
  14. yBegin = 0
  15. yEnd = n - 1
  16. self.circle(res,matrix, xBegin, xEnd, yBegin, yEnd)
  17. return res
  18. def circle(self, res, matrix, xBegin, xEnd, yBegin, yEnd):
  19. if xBegin <= xEnd and yBegin <= yEnd:
  20. if yBegin <= yEnd and xBegin <= xEnd: #这一行可以不需要,去掉会加速很多
  21. for i in xrange(yBegin, yEnd+1):
  22. res.append(matrix[xBegin][i])
  23. xBegin += 1
  24. if xBegin <= xEnd and yBegin <= yEnd:
  25. for i in xrange(xBegin, xEnd+1):
  26. res.append(matrix[i][yEnd])
  27. yEnd -= 1
  28. if yBegin <= yEnd and xBegin <= xEnd:
  29. for j in xrange(yEnd, yBegin-1, -1):
  30. res.append(matrix[xEnd][j])
  31. xEnd -= 1
  32. if xBegin <= xEnd and yBegin <= yEnd:
  33. for j in xrange(xEnd, xBegin-1, -1):
  34. res.append(matrix[j][yBegin])
  35. yBegin += 1
  36. self.circle(res,matrix, xBegin, xEnd, yBegin, yEnd)

转载于:https://www.cnblogs.com/sherylwang/p/5813219.html

发表评论

表情:
评论列表 (有 0 条评论,257人围观)

还没有评论,来说两句吧...

相关阅读