其他分享
首页 > 其他分享> > [LintCode] 611. Knight Shortest Path

[LintCode] 611. Knight Shortest Path

作者:互联网

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 destination cannot be reached.

Example

Example 1:

Input:
[[0,0,0],
 [0,0,0],
 [0,0,0]]
source = [2, 0] destination = [2, 2] 
Output: 2
Explanation:
[2,0]->[0,1]->[2,2]

Example 2:

Input:
[[0,1,0],
 [0,0,1],
 [0,0,0]]
source = [2, 0] destination = [2, 2] 
Output:-1

Clarification

If the knight is at (xy), he can get to the following positions in one step:

(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)

Notice

source and destination must be empty.
Knight can not enter the barrier.
Path length refers to the number of steps the knight takes.

 
/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */

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 row = 0;
    int col = 0;
    public int shortestPath(boolean[][] grid, Point source, Point destination) {
        // write your code here
        row = grid.length;
        col = grid[0].length;
        Queue<Point> queue = new LinkedList<>();
        int step = 0;

        int[][] directions = new int[][]{{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
        queue.offer(source);
        grid[source.x][source.y] = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                Point cur = queue.poll();
                if (cur.x == destination.x && cur.y == destination.y) {
                    return step;
                }
                for (int[] dir: directions) {
                    int newX = dir[0] + cur.x;
                    int newY = dir[1] + cur.y;
                    Point newP = new Point(newX, newY);
                    if (isValid(newP, grid)) { 
                        queue.offer(newP);
                        grid[newX][newY] = true;
                    }
                }
            }
            step += 1;
        }
        return -1;
    }
    
    private boolean isValid(Point p, boolean[][] visited) {
        if (p.x < 0 || p.x >= row || p.y < 0 || p.y >= col || visited[p.x][p.y]) {
            return false;
        }
        return true;
    }
}

 

标签:611,return,Point,int,Knight,destination,LintCode,source,grid
来源: https://www.cnblogs.com/xuanlu/p/12530765.html