gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:20 25 4
gpt4 key购买 nike

我使用维基百科的伪代码在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com