611. Knight Shortest Path(lintcode)

题目

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 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 (x, y), 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.

我的想法

典型的BFS层级遍历题。因为这里需要返回的是需要多少步,这个步数即层数

/**
 * 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 {
    public int shortestPath(boolean[][] grid, Point source, Point destination) {
        Queue<Point> queue = new LinkedList<>();
        int[] dircX = {1,1,-1,-1,2,2,-2,-2};
        int[] dircY = {2,-2,2,-2,1,-1,1,-1};
        queue.offer(source);
        grid[source.x][source.y] = true;
        
        int steps = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                Point cur = queue.poll();
                //should pay attention to the relationship between 
                //determination of destination and the increase of steps
                if(cur.x == destination.x && cur.y == destination.y) {
                    return steps;
                }
                for(int dirc = 0; dirc < 8; dirc++) {
                    Point newPoint = new Point(
                        cur.x + dircX[dirc], 
                        cur.y + dircY[dirc]
                    );
                    if(!inBound(newPoint, grid) || grid[newPoint.x][newPoint.y] == true) {
                        continue;
                    }
                    queue.offer(newPoint);
                    grid[newPoint.x][newPoint.y] = true;
                }
            }
            steps++;
        }
        return -1;
    }
    private boolean inBound(Point cur, boolean[][] grid) {
        if(cur.x < 0 || cur.x >= grid.length || cur.y < 0 || cur.y >= grid[0].length) {
            return false;
        }
        return true;
    }
}

这种棋盘型题目也可以用DP来做,等学到DP再来补写吧~

解答

BFS & DP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值