https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-interview-150
package leetcode150 import "testing" func TestSpiralOrder(t *testing.T) { matrix := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} res := spiralOrder(matrix) for _, re := range res { print(re) print(" ") } } func spiralOrder(matrix [][]int) []int { if len(matrix) == 0 || len(matrix[0]) == 0 { return []int{} } ans := make([]int, 0) left, right, top, bottom := 0, len(matrix[0])-1, 0, len(matrix)-1 total, sum := 0, len(matrix)*len(matrix[0]) for true { for i := left; i <= right; i++ { ans = append(ans, matrix[top][i]) total++ } top++ if total == sum { break } for i := top; i <= bottom; i++ { ans = append(ans, matrix[i][right]) total++ } right-- if total == sum { break } for i := right; i >= left; i-- { ans = append(ans, matrix[bottom][i]) total++ } bottom-- if total == sum { break } for i := bottom; i >= top; i-- { ans = append(ans, matrix[i][left]) total++ } left++ if total == sum { break } } return ans }
浙公网安备 33010602011771号