40 lines
681 B
Go
40 lines
681 B
Go
package q54
|
|
|
|
import "math"
|
|
|
|
var dirs = [4][2]int{
|
|
{1, 0}, // right
|
|
{0, 1}, // down
|
|
{-1, 0}, // left
|
|
{0, -1}, // up
|
|
}
|
|
|
|
const VISITED = math.MinInt
|
|
|
|
func spiralOrder(matrix [][]int) []int {
|
|
w, h := len(matrix[0]), len(matrix)
|
|
cnt := w * h
|
|
ret := make([]int, cnt)
|
|
|
|
x, y := 0, 0
|
|
dir := 0
|
|
vect := dirs[dir]
|
|
|
|
for i := range cnt {
|
|
ret[i] = matrix[y][x]
|
|
matrix[y][x] = VISITED
|
|
|
|
// Can move?
|
|
nextX, nextY := x+vect[0], y+vect[1]
|
|
if nextX < 0 || nextY < 0 || nextX == w || nextY == h || matrix[nextY][nextX] == VISITED {
|
|
dir = (dir + 1) % 4
|
|
vect = dirs[dir]
|
|
nextX, nextY = x+vect[0], y+vect[1]
|
|
}
|
|
x, y = nextX, nextY
|
|
}
|
|
|
|
return ret
|
|
}
|
|
|
|
var _ = spiralOrder
|