54. 螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 2:
输入: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]
//时间Omn,空间Omnfunc spiralOrder(matrix [][]int) []int {if len(matrix) == 0 {return []int{}}res := []int{}top, bottom := 0, len(matrix) -1left, right := 0, len(matrix[0]) -1for top <= bottom && left <= right {for i := left; i <= right; i++ {res = append(res, matrix[top][i])}top++for i := top; i <= bottom; i++ {res = append(res, matrix[i][right])}right--if top > bottom || left > right {break}for i := right; i >= left; i-- { //注意:这里i--,也变成bot相反res = append(res, matrix[bottom][i])}bottom--for i := bottom; i >= top; i-- {res = append(res,matrix[i][left])}left++}return res}
