add new solutions
This commit is contained in:
parent
d798d5e8c9
commit
886b5e0a8e
34 changed files with 1164 additions and 0 deletions
40
solutions/0/q54/solution.go
Normal file
40
solutions/0/q54/solution.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
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
|
||||
Loading…
Add table
Add a link
Reference in a new issue