-
Notifications
You must be signed in to change notification settings - Fork 396
/
Copy pathminimumKnightMoves.java
44 lines (34 loc) · 1.24 KB
/
minimumKnightMoves.java
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
//BFS Solution
class Solution {
private final int[][] DIRECTIONS = new int[][] {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};
public int minKnightMoves(int x, int y) {
x = Math.abs(x);
y = Math.abs(y);
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] {0, 0});
Set<String> visited = new HashSet<>();
visited.add("0,0");
int result = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.remove();
int curX = cur[0];
int curY = cur[1];
if (curX == x && curY == y) {
return result;
}
for (int[] d : DIRECTIONS) {
int newX = curX + d[0];
int newY = curY + d[1];
if (!visited.contains(newX + "," + newY) && newX >= -1 && newY >= -1) {
queue.add(new int[] {newX, newY});
visited.add(newX + "," + newY);
}
}
}
result++;
}
return -1;
}
}