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

 

转载于:https://www.cnblogs.com/codingEskimo/p/7025638.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值