Array - 54. Spiral Matrix

73

54.Spiral Matrix

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

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

思路:

题目意思是螺旋打印矩阵,思路就是从左往右,从上往下,再从右往左,最后从下往上打印,然后更新边界,递归或者迭代就可以。

第一次在面试官面前直播代码,紧张的不行,以后得稳着点,瞬间脑子都不转了. ?

代码:

go:

func spiralOrder(matrix [][]int) []int {
    var  res []int
    if matrix == nil || len(matrix) == 0 {
        return res
    }
    printGrid(matrix, 0, len(matrix) -1, 0, len(matrix[0]) - 1, &res)
    return res
}

func printGrid(grid [][]int, top, bottom, left, right int, res *[]int) {
    // 递归出口
    if top > bottom || left > right {
        return 
    }   
    
    if top == bottom {  // 1. 只有一列的情况
      for i := left; i <= right; i++ {
        *res = append(*res, grid[top][i])
      }
    } else if left == right {  // 2. 只有一行的情况
      for i := top; i <= bottom; i++ {
        *res = append(*res, grid[i][left])
      }
    } else {  // 3.正常绕圈打印
      // 从左往右打印
      for i := left; i <= right - 1; i++ {
          *res = append(*res, grid[top][i])
      }
        
      // 从上往下打印
      for i := top; i <= bottom - 1; i++ {
          *res = append(*res, grid[i][right])
      }

      // 从右往左打印
      for i := right; i >= left + 1; i-- {
          *res = append(*res, grid[bottom][i])
      }
        
      // 从下往上打印
      for i := bottom; i >= top + 1; i-- {
          *res = append(*res, grid[i][left])
      }
    }
    
    printGrid(grid, top+1, bottom-1, left+1, right-1, res)
}