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
|
func minKnightMoves(x int, y int) int {
x, y = abs(x), abs(y)
dirs := [8][2]int{{1,2},{2,1},{-1,2},{-2,1},{1,-2},{2,-1},{-1,-2},{-2,-1}}
type state struct{ x, y int }
q := []state{{0,0}}
vis := map[state]struct{}{{0,0}: {}}
steps := 0
for len(q) > 0 {
nq := []state{}
for _, s := range q {
if s.x == x && s.y == y { return steps }
for _, d := range dirs {
nx, ny := s.x+d[0], s.y+d[1]
ns := state{nx,ny}
if nx >= -2 && ny >= -2 && nx <= x+2 && ny <= y+2 {
if _, ok := vis[ns]; !ok {
vis[ns] = struct{}{}
nq = append(nq, ns)
}
}
}
}
q = nq
steps++
}
return -1
}
func abs(a int) int { if a < 0 { return -a }; return a }
|