Knight Shortest Path
Given a knight in a chessboard (a binary matrix with 0 as empty and 1 as barrier) with a source position, find the shortest path to a destination position, return the length of the route. Return -1 if knight can not reached.
If the knight is at (x, y), he can get to the following positions in one step:
(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)
Example:
[[0,0,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2] return 2
[[0,1,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2] return 6
[[0,1,0],
[0,0,1],
[0,0,0]]
source = [2, 0] destination = [2, 2] return -1
Solution:
Using BFS search. Start from the first level and check wether the destination is in the first level of moves or not. If destination is not in the first level of moves, then try the next level.
Code:
public class Solution {
private static int[] xmoves = {1,1,-1,-1,2,2,-2,-2};
private static int[] ymoves = {2,-2,2,-2,1,-1,1,-1};
public int shortestPath(boolean[][] grid, Point source, Point destination) {
int steps = -1;
Queue<Point> q = new LinkedList<>();
q.offer(source);
while (!q.isEmpty()) {
steps++;
int size = q.size();
for (int i = 0; i < size; i++) {
Point p = q.poll();
if (p.x == destination.x && p.y == destination.y) {
return steps;
}
for (int j = 0; j < xmoves.length; j++) {
Point temp = new Point(p.x + xmoves[j], p.y + ymoves[j]);
addToQueue(grid, temp, q);
}
}
}
return -1;
}
private void addToQueue(boolean[][] grid, Point p, Queue<Point> q) {
if (p.x < 0 || p.x >= grid.length || p.y < 0 || p.y >= grid[p.x].length) {
return;
}
if (!grid[p.x][p.y]) {
grid[p.x][p.y] = true;
q.offer(p);
}
}
}