Knight Shortest Path

来源:互联网 发布:淘宝添加到桌面没有了 编辑:程序博客网 时间:2024/05/01 10:11

Given a knight in a chessboard (a binary matrix with 0 as empty and 1 as barrier) with a source position, find the shortest path to a destination position, return the length of the route.
Return -1 if knight can not reached.

/** * 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      */    public int shortestPath(boolean[][] grid, Point source, Point destination) {        if (grid == null || grid.length == 0 || grid[0].length == 0) {            return -1;        }        int n = grid.length;        int m = grid[0].length;        int[] directionX = {1, 1, -1, -1, 2, 2, -2, -2};        int[] directionY = {2, -2, 2, -2, 1, -1, 1, -1};        Queue<Point> queue = new LinkedList<>();        queue.offer(source);        int step = 0;        while (!queue.isEmpty()) {            int size = queue.size();            step++;            for (int i = 0; i < size; i++) {                Point point = queue.poll();                for (int j = 0; j < 8; j++) {                    Point adj = new Point(                        point.x + directionX[j],                        point.y + directionY[j]                    );                    if (inBound(adj.x, adj.y, grid)) {                        if (adj.x == destination.x && adj.y == destination.y) {                            return step;                        }                        //走过的点不能再走了,抹掉                        grid[adj.x][adj.y] = true;                        queue.offer(adj);                    }                }            }        }        return -1;    }    private boolean inBound(int x, int y, boolean[][] grid) {        int n = grid.length;        int m = grid[0].length;        return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == false;    }}
0 0
原创粉丝点击