c++ - 如何使用 BFS 找到两个节点之间的距离?

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

我使用维基百科的伪代码在 C++ 中编写了这段 BFS 代码。 该函数有两个参数 s,t。其中 s 是源节点,t 是目标,如果目标是 fount,则搜索返回目标本身,否则返回 -1。 这是我的代码:

#include <iostream>
#include <deque>
#include <vector>

using namespace std;

struct vertex{
vector<int> edges;
bool visited;
};

int dist = 0;

int BFS(vertex Graph[],int v,int target){
deque<int> Q;
Q.push_front(v);
Graph[v].visited = true;
    while(!Q.empty()){
        int t = Q.back();
        Q.pop_back();
            if(t == target){
                return t;
            }
            for(unsigned int i = 0;i < Graph[t].edges.size();i++){
                int u = Graph[t].edges[i];
                if(!Graph[u].visited){
                    Graph[u].visited = true;
                    Q.push_front(u);
                }
            }
    }
    return -1;
} 

int main(){
int n;
cin >> n;
vertex Graph[n];
int k;
cin >> k;
for(int i = 0;i < k; i++){
    int a,b;
    cin >> a >> b;
    a--;
    b--;
    Graph[a].edges.push_back(b);
    Graph[b].edges.push_back(a);
}

for(int i = 0;i < n; i++){
    Graph[i].visited = false;
}

int s,t;
cin >> s >> t;

cout << BFS(Graph,s,t);

  }

我在维基百科上读到过这个:

Breadth-first search can be used to solve many problems in graph theory, for example:
Finding the shortest path between two nodes u and v (with path length measured by number > > of edges)

我如何更改我的 BFS 函数以返回从 s 到 t 的最短路径,如果不存在路径则返回 -1?

最佳答案

根据定义,广度优先搜索先访问距离起点 d 的所有节点,然后再访问距离 d+1 的任何节点。因此,当您以广度优先顺序遍历图时,第一次遇到目标节点时,您已经通过最短路径到达了那里。

内森 S.'答案是正确的,但我希望这个答案能提供更多关于为什么这样做的直觉。 Paul Dinh 的评论也是正确的;您可以非常简单地修改 Nathan 的答案以跟踪距离而不是实际路径。

关于c++ - 如何使用 BFS 找到两个节点之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171038/

相关文章:

c++ - std 集合上的 CPPUNIT_ASSERT_EQUAL

c++ - 调用外部代码

c++ - 如何让lcov执行得更快?

algorithm - 图上权重变化的最短路径

c++ - 编译错误。如何使用 lex/yacc 解析变量名?

python - 查找图中所有不存在的连接

c++ - 图论的 C++ 库列表

algorithm - 准备一个时间表,以便在最短的时间内教授所有类(class)

algorithm - 最小生成树和最短路径树的区别

algorithm - 为什么 Dijkstra 算法不适用于负权重边?