-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnightShortestPath.java
More file actions
91 lines (75 loc) · 2.42 KB
/
KnightShortestPath.java
File metadata and controls
91 lines (75 loc) · 2.42 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.LinkedList;
import java.util.Queue;
class Point {
int x;
int y;
Point() {
x = 0;
y = 0;
}
Point(int a, int b) {
x = a;
y = b;
}
}
public class KnightShortestPath {
/**
* @param grid: a chessboard included 0 (false) and 1 (true)
* @param source: a point
* @param destination: a point
* @return: the shortest path
*/
public int shortestPath(boolean[][] grid, Point source, Point destination) {
// write your code here
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
int[][] moveArray = new int[][] { { 1, 2 }, { 1, -2 }, { -1, 2 }, { -1, -2 }, { 2, 1 }, { 2, -1 }, { -2, 1 },
{ -2, -1 } };
Queue<Point> q = new LinkedList<>();
q.offer(source);
int step = 0;
if (source.x == destination.x && source.y == destination.y) {
return 0;
}
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Point p = q.poll();
for (int j = 0; j < 8; j++) {
Point newPoint = new Point(p.x + moveArray[j][0], p.y + moveArray[j][1]);
if (inBound(newPoint, m, n) && grid[newPoint.x][newPoint.y] == false) {
if (newPoint.x == destination.x && newPoint.y == destination.y) {
return step + 1;
}
q.offer(newPoint);
grid[newPoint.x][newPoint.y] = true;
} else {
continue;
}
}
}
step++;
}
return -1;
}
private boolean inBound(Point p, int m, int n) {
if (p.x < 0 || p.x >= n) {
return false;
}
if (p.y < 0 || p.y >= m) {
return false;
}
return true;
}
public static void main(String[] args) {
KnightShortestPath k = new KnightShortestPath();
boolean[][] grid = new boolean[][] { { false, false, false }, { false, false, false },
{ false, false, false } };
Point s = new Point(2, 0);
Point d = new Point(2, 2);
System.out.println(k.shortestPath(grid, s, d));
}
}