java - 骑士的最短路径(BFS)

标签 java breadth-first-search

请帮助我理解我的代码做错了什么。我试图使用 BFS 获得最短路径来解决问题,但它要么给我 -1 要么 2。它应该给我 6 作为答案。我究竟做错了什么?这就是问题所在:

给定一个棋盘,找到马从给定来源到达给定目的地所采取的最短距离(最小步数)。

例如,N = 8(8 x 8 板),源 = (7, 0) 目标 = (0, 7)

所需的最少步骤数为 6

我的代码如下:

class Point {
    int x, y;
    public Point(int x, int y){
    this.x = x;
    this.y = y;
 }
}

class knightShortestPath {
    int N = 8;
    public static boolean visited[][];

public boolean isPositionValid(int x, int y){
    if( x < 0 || y < 0 || x > this.N || y > this.N){
        return false;
    }
    return true;
}

public void createChessBoard(int N) {
    this.N = N;
    visited = new boolean[this.N][this.N];
    for (int i = 0; i < this.N; i++) {
        for (int j = 0; j < this.N; j++) {
            visited[i][j] = false;
        }
    }
}

public int BFS(Point source, Point destination) {
    int row[] = {2, 2, -2, -2, 1, 1, -1, -1};
    int col[] = {1, -1, 1, -1, 2, -2, 2, -2};
    Queue<Point> queue = new LinkedList<>();
    queue.offer(source);
    visited[source.x][source.y] = true;
    int minimumNumSteps = 0;

    while (!queue.isEmpty()) {
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            Point pt = queue.poll();
            if (pt.x == destination.x && pt.y == destination.y) {
                return minimumNumSteps;
            }
            for (int j = 0; j < size; j++) {
                Point next = new Point(pt.x + row[i], pt.y + col[j]);
                if (isPositionValid(pt.x + row[i], pt.y + col[j]) && !visited[i][j]) {
                    visited[i][j] = true;
                    queue.offer(next);
                }
            }
        }
        minimumNumSteps++;
    }
    return minimumNumSteps;
}


public static void main(String[] args) {
    knightShortestPath position = new knightShortestPath();
    position.createChessBoard(8);
    Point src = new Point(0,7);
    Point dest = new Point(7,0);
    System.out.println("The minimum number of steps are: " + position.BFS(src, dest)); //answer is 6
 }
}

最佳答案

第一件事:我不知道你怎么会得到负值。用 0 初始化后,您永远不会减少 minimumNumSteps。可能会溢出吗?我觉得很奇怪..

除此之外,我还发现两个问题:

  1. 两个 for 循环不正确。您当前正在迭代 queue.size()。相反,您想要做的是迭代当前节点的所有子节点。
  2. 在 for 循环之外轮询当前点。

所以:

while(!queue.isEmpty()) {
    Point pt = queue.poll();
    // check if it's target 
    // ...
    for (int i = 0; i < row.length; i++) {
        // ... 
        for (int j = 0; j < col.length; j++) {
            // ...
        }
    }
}

另外注意:当队列为空并且你还没有达到目标时,没有解决办法。目前,您返回的一些值可能会被错误地解释。

关于java - 骑士的最短路径(BFS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52812615/

相关文章:

java - 给定一个有向图,找出两个节点之间是否存在路径

c++ - 如何在矩阵上实现 bfs?

prolog - 在 Prolog 中使用广度优先搜索 (BFS) 解决食人族/传教士问题?

java - BFS : PriorityQueue not getting empty

Java可变函数参数

java - 如何在 persistence.xml 中添加数据源以便 IntelliJ IDEA 看到它?

java - 重新初始化 transient 变量的正确方法

java - 为什么以下语句返回 true?

java - XML 编码 + 项目结构

java - 寻找 Hook Xposed 模块的方法