54. 螺旋矩阵

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 2:
54. 螺旋矩阵 👌 - 图1
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

  1. //时间Omn,空间Omn
  2. func spiralOrder(matrix [][]int) []int {
  3. if len(matrix) == 0 {
  4. return []int{}
  5. }
  6. res := []int{}
  7. top, bottom := 0, len(matrix) -1
  8. left, right := 0, len(matrix[0]) -1
  9. for top <= bottom && left <= right {
  10. for i := left; i <= right; i++ {
  11. res = append(res, matrix[top][i])
  12. }
  13. top++
  14. for i := top; i <= bottom; i++ {
  15. res = append(res, matrix[i][right])
  16. }
  17. right--
  18. if top > bottom || left > right {
  19. break
  20. }
  21. for i := right; i >= left; i-- { //注意:这里i--,也变成bot相反
  22. res = append(res, matrix[bottom][i])
  23. }
  24. bottom--
  25. for i := bottom; i >= top; i-- {
  26. res = append(res,matrix[i][left])
  27. }
  28. left++
  29. }
  30. return res
  31. }