实现代码:
#include<iostream>
#include<queue>
using namespace std;
#define inf 0x3f3f3f
const int N = 155;
int G[N][N];
int n, m;
bool book[N];
int dis[N];
int path[N];
queue<int>q;
void bfs(int x) {
book[x] = true;
q.push(x);
while (!q.empty()) {
for (int i = 0;i < n;i++) {
if (book[i] == false && G[q.front()][i] == 1) {
book[i] = true;
q.push(i);
path[i] = q.front();
dis[i] = dis[q.front()] + 1;
}
}
q.pop();
}
}
int main() {
cin >> n >> m;
for (int i = 0;i < n;i++)
book[i] = false;
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++) {
G[i][j] = 0;
G[j][i] = 0;
}
}
for (int i = 0;i < m;i++) {
int x, y;
cin >> x >> y;
G[x][y] = 1;
G[y][x] = 1;
}
for (int i = 0;i < n;i++) {
dis[i] = inf;
path[i] = -1;
}
dis[1] = 0;
bfs(1);
for (int i = 0;i < n;i++) {
cout <<"从1号顶点到达顶点"<<i<<"的最短路径长度为:"<<dis[i] << ","<<"路径为:"<<i;
int t = i;
while (path[t] != -1) {
cout << "<-" << path[t];
t = path[t];
}
cout << endl;
}
return 0;
}
运行结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/872fad89bf77b588bcb74cb2571f9173.png)