Knight Shortest Path

本文介绍了一种算法,用于解决棋盘上骑士从源位置到目标位置的最短路径问题。通过广度优先搜索(BFS)遍历所有可能的移动方式,考虑障碍物的存在,并返回最短路径长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值