我使用维基百科的伪代码编写了以下c++ BFS代码。
该函数接受两个参数s和t。其中s是源节点,t是目标节点。如果找到目标节点,则返回目标本身,否则返回-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);
}
我在维基百科上看到这篇文章:
广度优先搜索可以用于解决图论中的许多问题,例如:
查找两个节点u和v之间的最短路径(路径长度由边数测量)
如何更改我的BFS函数以返回从s到t的最短路径,并在不存在路径时返回-1?