#include <iostream>
#include <queue>
#include <cstring> // for memset
#define Max 503
#define INF 0xcffff
using namespace std;
typedef struct AMGraph {
int vex, arc;
int arcs[Max][Max];
} AMGraph;
queue<int> a;
bool visited[Max];
int dist[Max];
int path[Max];
int firstnode(AMGraph& G, int x) {
for (int i = 1; i <= G.vex; i++) {
if (G.arcs[x][i] > 0 && !visited[i])
return i;
}
return -1;
}
int nextnode(AMGraph& G, int x, int next) {
for (int i = next + 1; i <= G.vex; i++) {
if (G.arcs[x][i] > 0 && !visited[i])
return i;
}
return -1;
}
void BFS(AMGraph& G, int x) {
for (int i = 1; i <= G.vex; i++) {
path[i] = -1;
dist[i] = INF;
visited[i] = false;
}
dist[x] = 0;
visited[x] = true;
a.push(x);
while (!a.empty()) {
int current = a.front();
cout << current << " ";
a.pop();
for (int w = firstnode(G, current); w > 0; w = nextnode(G, current, w)) {
if (!visited[w]) {
a.push(w);
visited[w] = true;
path[w] = current;
dist[w] = dist[current] + 1;
}
}
}
cout << endl;
}
void find(int x) {
if (path[x] == -1) {
cout << x;
}
else {
find(path[x]);
cout << "->" << x;
}
}
void putin(AMGraph& G) {
int u, v;
cin >> G.vex >> G.arc;
for (int i = 1; i <= G.vex; i++) {
for (int j = 1; j <= G.vex; j++) {
if (i == j) G.arcs[i][j] = 0;
else G.arcs[i][j] = -1; // 初始化为-1,表示无边
}
}
for (int i = 0; i < G.arc; i++) {
cin >> u >> v;
G.arcs[u][v] = 1;
G.arcs[v][u] = 1;
}
}
void putout(AMGraph& G, int x) {
cout << "dist[]: ";
for (int i = 1; i <= G.vex; i++) {
cout << dist[i] << " ";
}
cout << endl;
for (int i = 1; i <= G.vex; i++) {
cout << "V" << x << "到V" << i << "的最短路徑是:" ;
find(i);
cout << endl;
}
}
int main() {
AMGraph G;
putin(G);
int point = 2;
BFS(G, point);
putout(G, point);
return 0;
}
/*
5 7
1 3
1 5
2 5
2 4
4 5
3 2
3 5
*/
需要的辅助数组太多了