funcspiralOrder(matrix [][]int) []int { n, m := len(matrix), len(matrix[0]) top, bottom, left, right := 0, n, 0, m ans := []int{} for left < right && top < bottom { for i := left; i < right; i++ { ans = append(ans, matrix[top][i]) } for i := top + 1; i < bottom; i++ { ans = append(ans, matrix[i][right - 1]) } if left < right - 1 && top < bottom - 1 { for i := right - 2; i >= left; i-- { ans = append(ans, matrix[bottom - 1][i]) } for i := bottom - 2; i > top; i-- { ans = append(ans, matrix[i][left]) } } left++ right-- top++ bottom-- } return ans }