题目:https://pintia.cn/problem-sets/1268384564738605056/problems/1281571555112456192
给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
输出格式:
按照"{ v1 v2 ... vk }"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。
输入样例:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
输出样例:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }
题解:https://blog.csdn.net/qq_40946921/article/details/99696249
代码:
#include<iostream> #include <set> #include <map> #include<queue> using namespace std; struct Node { bool visited = false; set<int> child; }; map<int, Node> mp; void dfs(const int& i) { cout << i << " "; mp[i].visited = true; for (auto& j : mp[i].child) if (!mp[j].visited) dfs(j); } void bfs(const int& i) { queue<int> q; q.push(i); mp[i].visited = true; while (!q.empty()) { cout << q.front() << " "; for(auto& j:mp[q.front()].child) if (!mp[j].visited) { mp[j].visited = true; q.push(j); } q.pop(); } } int main(){ int n, m, a, b; cin >> n >> m; for (int i = 0; i < m; ++i) { cin >> a >> b; mp[a].child.insert(b); mp[b].child.insert(a); } for (int i = 0; i < n; i++) { if (!mp[i].visited) { cout << "{ "; dfs(i); cout << "}" << endl; } mp[i].visited = false; } for (int i = 0; i < n; ++i) { if (!mp[i].visited) { cout << "{ "; bfs(i); cout << "}" << endl; } } return 0; }