和59一样,但每次更新count后要check是否达到目标数了,达到则返回:
func spiralOrder(matrix [][]int) []int {
m, n := len(matrix), len(matrix[0])
res := make([]int, m * n)
top, bottom := 0, m - 1
left, right := 0, n - 1
count := 0
for count < m * n {
// left-right
for x := left; x <= right; x++ {
res[count] = matrix[top][x]
count++
if count >= m * n { return res }
}
top++
// top-bottom
for y := top; y <= bottom; y++ {
res[count] = matrix[y][right]
count++
if count >= m * n { return res }
}
right--
// right-left
for x := right; x >= left; x-- {
res[count] = matrix[bottom][x]
count++
if count >= m * n { return res }
}
bottom--
// bottom-top
for y := bottom; y >= top; y-- {
res[count] = matrix[y][left]
count++
if count >= m * n { return res }
}
left++
}
return res
}