BFS求解非加权图单源最短路径问题(邻接表)(C++实现)
实现代码
/*
author : eclipse
email : [email protected]
time : Sat Apr 18 22:48:00 2020
*/
#include<bits/stdc++.h>
using namespace std;
const int INF = 0xFFFF;
vector< vector<int> > adjacentList;
vector<int> dist;
vector<int> path;
void BFSMinDistance(int source) {
vector<bool> tag;
int vexNum = adjacentList.size();
tag.resize(vexNum);
for (int i = 0; i < vexNum; i++) {
dist[i] = (i == source ? 0 : INF);
tag[i] = (i == source ? true : false);
path[i] = (i == source ? source + 1 : -1);
}
queue<int> q;
q.push(source);
while (!q.empty()) {
int front = q.front();
q.pop();
for (int i = 0; i < adjacentList[front].size(); i++) {
int to = adjacentList[front][i];
if (!tag[to] ) {
tag[to] = true;
dist[to] = dist[front] + 1;
path[to] = front + 1;
q.push(to);
}
}
}
}
void print() {
printf("Shortest path\n");
for (int i = 0; i < path.size(); i++) {
printf("%d ", path[i]);
}
printf("\nShortest dist\n");
for (int i = 0; i < dist.size(); i++) {
printf("%d ", dist[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int from, to;
int vexNum;
int edgeNum;
int source;
while (~scanf("%d%d%d", &vexNum, &edgeNum, &source)) {
adjacentList.resize(vexNum);
path.resize(vexNum);
dist.resize(vexNum);
for (int i = 0; i < edgeNum; i++) {
scanf("%d%d", &from, &to);
adjacentList[from - 1].push_back(to - 1);
}
BFSMinDistance(source - 1);
print();
adjacentList.clear();
path.clear();
dist.clear();
}
return 0;
}
算法思路
- 算法思路
利用BFS算法可以求解非加权图的单源最短路问题,dist数组对应值继承其上一个邻接顶点的dist值并加1,源点source对应dist数组的值为0 - 注释
主要代码及注释与BFS算法相似,在此不再赘述 - 样例
测试数据与Dijkstra,Floyd,Bellman-ford等算法的样例相似,再次便不再赘述 - Dijkstra算法
- Bellman-ford算法
- BFS算法
测试数据
5 6 1
1 2
1 4
2 3
2 5
3 4
3 5
3 5 1
1 2
1 3
2 1
2 3
3 1
输出结果
Shortest path
1 1 2 1 2
Shortest dist
0 1 2 1 2
Shortest path
1 1 1
Shortest dist
0 1 1
鸣谢
感谢王道论坛及其产品提供的宝贵建议和测试样例
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!