Knight Shortest Path

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;
        
    }
}

最后更新于

这有帮助吗?