-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathknightMoves.py
52 lines (41 loc) · 1.57 KB
/
knightMoves.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
q = deque([(0,0,0)])
visited = set()
moves = ((2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1))
while q:
px, py, cnt = q.pop()
if px == abs(x) and py == abs(y):
return cnt
for dx, dy in moves:
px1 = px+dx
py1 = py+dy
if (px1,py1) not in visited and px1 >= -2 and py1 >= -2:
q.appendleft((px1, py1,cnt+1))
visited.add((px1, py1))
return -1
def minKnightMoves1(self, x: int, y: int) -> int:
x, y = abs(x), abs(y)
res = 0
while x > 4 or y > 4:
res += 1
if x >= y:
x -= 2
y -= 1 if y >= 1 else -1
else:
x -= 1 if x >= 1 else -1
y -= 2
q = deque([(0,0,0)])
visited = set()
moves = ((2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1))
while q:
px, py, cnt = q.pop()
if px == abs(x) and py == abs(y):
return cnt + res
for dx, dy in moves:
px1 = px+dx
py1 = py+dy
if (px1,py1) not in visited and px1 >= -2 and py1 >= -2:
q.appendleft((px1, py1,cnt+1))
visited.add((px1, py1))
return -1