Given a knight in a chessboard (a binary matrix with0as empty and1as barrier) with asourceposition, find the shortest path to adestinationposition, return the length of the route.
Return-1if knight can not reached.
国际象棋棋盘中骑士只能走对角线。
Notice
source and destination must be empty.
Knight can not enter the barrier.
Clarification
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)
class Point {
public int x, y;
public Point() { x = 0; y = 0; }
public Point(int a, int b) { x = a; y = b; }
}
public class Solution {
/**
* @param grid a chessboard included 0 (false) and 1 (true)
* @param source, destination a point
* @return the shortest path
*/
public int m,n;
public int[] deltaX={2,2,-2,-2,1,1,-1,-1};
public int[] deltaY={1,-1,1,-1,2,-2,2,-2};
public int shortestPath(boolean[][] grid, Point source, Point destination) {
if(grid==null || grid.length==0 || grid[0].length==0){
return -1;
}
m=grid.length;
n=grid[0].length;
Queue<Point> queue=new LinkedList<Point>();
queue.offer(source);
int step=0;
while(!queue.isEmpty()){
//use size to store level(step)
int size=queue.size();
for(int i=0;i<size;i++){
Point current=queue.poll();
if(current.x==destination.x && current.y==destination.y){
return step;
}
//loop to find its neighbor which can reachable
for(int direction=0;direction<8;direction++){
Point neighbor=new Point(current.x+deltaX[direction],current.y+deltaY[direction]);
//check it if it can reachable
if(!inBound(neighbor,grid)){
continue;
}
queue.offer(neighbor);
//Make it not accessible
grid[neighbor.x][neighbor.y]=true;
}
}
// every level to add 1 step.
step++;
}
return -1;
}
public boolean inBound(Point point,boolean[][] grid){
if(point.x<0 || point.x>=m){
return false;
}
if(point.y<0 || point.y>=n){
return false;
}
return (grid[point.x][point.y]==false);
}
}