# Knight Shortest Path

{% tabs %}
{% tab title="Java" %}

```java
public class Solution {
    /**
     * @param grid: a chessboard included 0 (false) and 1 (true)
     * @param source: a point
     * @param destination: a point
     * @return: the shortest path 
     */
        
        int[] dx = {1, 1, -1, -1, 2, 2, -2, -2};
        int[] dy = {2, -2, 2, -2, 1, -1, 1, -1};
    public int shortestPath(boolean[][] grid, Point source, Point destination) {
        
        
        Queue<Point> queue = new LinkedList<>();
        boolean[][] v = new boolean [grid.length + 1][grid[0].length + 1];
        queue.offer(source);
        int res =0;
        while(!queue.isEmpty()){
            
            int size = queue.size(); 
            res++;
            for(int i = 0; i < size; i++){
                Point cur = queue.poll();
                int x = cur.x, y = cur.y;
                
                
                for(int k = 0; k < 8; k ++){
                    
                    Point nextPoint = new Point(
                    x + dx[k],
                    y + dy[k]);
                    if(nextPoint.x < 0 || nextPoint.x >= grid.length || nextPoint.y<0 || nextPoint.y >= grid[0].length || grid[nextPoint.x][nextPoint.y] || v[nextPoint.x][nextPoint.y]){
                     continue;
                    }  
                    if(nextPoint.x == destination.x && nextPoint.y == destination.y){
                        return res;
                    }
                    queue.offer(nextPoint);
                    v[nextPoint.x][nextPoint.y] = true;
                }
            }
        }
        return -1;
        
    }
}
```

{% endtab %}
{% endtabs %}

![](https://2784211123-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M-ELB26IpzCEJWSDi0m%2F-M-ELbsic2B8wwsarT-C%2F-M-EMqc6UhBUlpM3zyHy%2F1580805867266.jpg?alt=media\&token=11a20b67-9e32-4c02-bf02-c405dac8ef0f)
