用top,bottom,left,right分别指向上下左右,然后向内循环收缩
    top所在行遍历完后,top+1
    rihgt所在列遍历完后,right-1
    bottom所在行遍历完后,bottom-1
    left所在列遍历完后,left+1

    1. package main
    2. import "fmt"
    3. func spiralOrder(matrix [][]int) []int {
    4. if len(matrix) == 0 {
    5. return nil
    6. }
    7. left :=0
    8. right :=len(matrix[0])-1
    9. top :=0
    10. bottom :=len(matrix)-1
    11. grid := make([]int,(right+1)*(bottom+1))
    12. index :=0
    13. for left<=right&&top<=bottom{
    14. // 上层 边界判断
    15. for i:=left;i<=right&&top<=bottom;i++{
    16. grid[index] = matrix[top][i]
    17. index++
    18. }
    19. //fmt.Println("top","=",grid)
    20. top++
    21. // 右侧
    22. for i:=top;i<=bottom&&left<=right;i++{
    23. grid[index]= matrix[i][right]
    24. index++
    25. }
    26. //fmt.Println("right","=",grid)
    27. right--
    28. //下
    29. for i:=right;i>=left&&top<=bottom;i--{
    30. grid[index]= matrix[bottom][i]
    31. index++
    32. }
    33. //fmt.Println("bottom","=",grid)
    34. bottom--
    35. //左
    36. for i:=bottom;i>=top&&left<=right;i--{
    37. grid[index]= matrix[i][left]
    38. index++
    39. }
    40. //fmt.Println("left","=",grid)
    41. left++
    42. //fmt.Println(grid)
    43. }
    44. return grid
    45. }
    46. func main() {
    47. matrix :=[][]int{{1,2,3,4},{5,6,7,8},{9,10,11,12}}
    48. fmt.Println("1","=",spiralOrder(matrix))
    49. }

    image.png