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

标签 c++ shortest-path breadth-first-search

我在矩阵上实现 bfs 时遇到问题。似乎我的代码只检查起始节点的子节点。

我的目标是找到从“B”到“H”的最短路径。我还认为我的代码需要大量修改。先感谢您!

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;

int bfs(int, int);

bool visited[100][100];
char matrica[100][100];

int m, n, d;

int main()
{

    scanf("%d %d", &m, &n);

    for(int i = 0;i < m;i++){
        for(int j = 0; j < n; j++){
            cin >> matrica[i][j];
            visited[i][j] = false;
        }
    }

    for(int i = 0;i < m;i++){
        for(int j = 0; j < n; j++){
            if(matrica[i][j] == 'B'){
                bfs(i, j);
            }
        }
    }

    cout << endl << d;

    return 0;
}

int gk[] = {1, 0, -1, 0};
int gr[] = {0, 1, 0, -1};

int bfs(int x, int y){

    cout << endl;

    queue<int>queue_x, queue_y;
    int topx, topy, d=0;

    //memset(visited, 0, sizeof visited);

    visited[x][y] = true;

    queue_x.push(x);
    queue_y.push(y);

    while(!queue_x.empty()){
        topx = queue_x.front();
        topy = queue_y.front();
        queue_x.pop();
        queue_y.pop();

        if(matrica[topx][topy] == 'H'){
            cout << endl << d << endl;
            d++;
            return d;
        }

        for(int i = 0; i < 4; i++){
            x += gk[i];
            y += gr[i];
            if(visited[x][y] == false && matrica[x][y] != '#'){
                visited[x][y] = true;
                matrica[x][y] = '*';
                queue_x.push(x);
                queue_y.push(y);
                d++;

                //-------------
                for(int i = 0; i < m;i++){
                    for(int j = 0; j < n;j++){
                        cout << matrica[i][j];
                    }
                    cout << endl;
                }
                //-------------
            }
        }
    }
}

输入/输出:

输入:

5
5
#####
#..B#
#...#
#...#
###H#

输出:

#####
#..B#
#...#
#...#
###H#
0

最佳答案

变量xy

x += gk[i];
y += gr[i];

不应该从一个迭代到下一个迭代“记住”它们的值。

将这些行更改为

x = topx + gk[i];
y = topy + gr[i];

关于c++ - 如何在矩阵上实现 bfs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22642902/

相关文章:

c++ - 如何在 blackberry 10 native 中获取 IMEI 号码

Google foo bar 的 Python 广度优先最短路径(准备兔子逃跑)

algorithm - 无向图和城市电源路径

algorithm - 即使在具有负边权重的图中,我们能否使用 Dijkstra 找到最短路径?

c# - 如何连接点和吸收动量?

algorithm - 如何在有向图中找到最短的有向环?

c++ - 关于c++中的析构函数

c++ - Apple Mach-O 链接器命令失败,退出代码为 1

c++ - 工厂类的依赖注入(inject)

python-3.x - 广度优先搜索 : Shortest Path using Python