Files
2024-12-06 01:56:28 +08:00

52 lines
1.8 KiB
C++

// 利用邻接表存储无向图,并从0号顶点开始进行广度优先遍历。
// 输入:
// 输入第一行是两个整数n e,其中n表示顶点数(则顶点编号为0至n-1),e表示图中的边数。
// 之后有e行输入,每行输入表示一条边,格式是“顶点1 顶点2”,把边插入图中。在链表中插入元素时,在链表头部插入。需要注意,由于是无向图,因此同一条边需要在两条链表中都插入。
// 例如:
// 4 4
// 0 1
// 1 3
// 0 3
// 0 2
// 输出:
// 先按0至n-1输出存储图的邻接表,每个链表占1行,同一行元素之间空1格,最后一个元素之后不要有空格。先输出顶点编号,之后按链表顺序输出相邻顶点编号。
// 之后空一行后输出从0号顶点开始的广度优先遍历序列,顶点编号之间空1格。
// 例如,对于上面的示例输入,输出为:
// 0 2 3 1
// 1 3 0
// 2 0
// 3 0 1
// 从顶点0开始的广度优先遍历序列:
// 0 2 3 1
// 说明:
// 输入第1个4表示有4个顶点,第2个4表示有4条边。之后的4行输入代表4条边的顶点。输出前4行为邻接表中的4个链表,之后空一行,然后输出的“0 2 3 1”是深度优先遍历序列。
#include"ListGraph.h"
#include<iostream>
using namespace std;
int main() {
ListGraph<int> graph = ListGraph<int>();
int n, e;
cin >> n >> e;
for (int i = 0; i < n; i++) {
graph.insert(i);
}
int id1, id2;
for (int i = 0; i < e; i++) {
cin >> id1 >> id2;
graph.connect(id1, id2);
}
cout << "邻接表:" << endl;
cout << graph.to_string() << endl;
cout << "BFS序列:" << endl;
vector<int> bfs = graph.BFS(0);
vector<int>::iterator it;
for (it = bfs.begin(); it != bfs.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}