1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| func spiralOrder(matrix [][]int) []int { res := []int{} top, bottom, left, right := 0, len(matrix)-1, 0, len(matrix[0])-1 for top <= bottom && left <= right { for j := left; j <= right; j++ { res = append(res, matrix[top][j]) } top++
for i := top; i <= bottom; i++ { res = append(res, matrix[i][right]) } right--
if top <= bottom { for j := right; j >= left; j-- { res = append(res, matrix[bottom][j]) } bottom-- }
if left <= right { for i := bottom; i >= top; i-- { res = append(res, matrix[i][left]) } left++ } } return res }
|