[LintCode] Knight Shortest Path

This question is standard level BSF. From this question, we can see the best time to mark a node is the time when it is added to a queue.

/**
 * Definition for a point.
 * public class Point {
 *     publoc 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 
     */
    private static final int[] DIRECTX = {1, 1, -1, -1, 2, 2, -2, -2};
    private static final int[] DIRECTY = {2, -2, 2, -2, 1, -1, 1, -1};
    public int shortestPath(boolean[][] grid, Point source, Point destination) {
        // Write your code here
        if (grid.length == 0 || source == null || destination == null || 
            grid[source.x][source.y] || grid[destination.x][destination.y]) {
            return -1;
        }
        
        int step = 0;
        Queue<Point> queue = new LinkedList<>();
        queue.offer(source);
        grid[source.x][source.y] = true;
        
        while (!queue.isEmpty()) {
            int n = queue.size();
            for (int i = 0; i < n; i++) {
                Point curPoint = queue.poll(); 
                if (curPoint.x == destination.x && curPoint.y == destination.y) {
                    return step;
                } else {
                    for (int direction = 0; direction < DIRECTX.length; direction++) {
                        Point neighbor = new Point(curPoint.x + DIRECTX[direction], 
                                               curPoint.y + DIRECTY[direction]);
                        if (isAvaliableStep(grid, neighbor)) {
                            queue.offer(neighbor);
                            //Once it is put in the queue, it is no longer avaliable.
                            //If you do not set here, ont Point could be access from different points, it will have duplicates.
                            grid[neighbor.x][neighbor.y] = true;
                        }    
                    }
                    
                }
            }
            step++;
        }
        return -1;
    }
    
    private boolean isAvaliableStep(boolean[][] grid, Point neighbor) {
        int x = neighbor.x;
        int y = neighbor.y;
        if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && !grid[x][y]) {
            return true;
        } else {
            return false;
        }
    }
}

 

posted on 2017-06-16 07:36  codingEskimo  阅读(121)  评论(0)    收藏  举报

导航