For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS (Depth First Search) and BFS (Breadth First Search). Assume that all the vertices are numbered from 0 to N-1. While searching, assume that we always start from the vertex with the smallest index, and visit its adjacent vertices in ascending order of their indices.
Input Specification:
Each input file contains one test case. For each case, the first line gives two integers N (0<N≤10) and E, which are the number of vertices and the number of edges, respectively. Then E lines follow, each described an edge by giving the two ends. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in each line a connected component in the format { v
1
v
2
… v
k
}. First print the result obtained by DFS, then by BFS.
Sample Input:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
Sample Output:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }
点数较少,可用矩阵存,这样也能保证顺序为从小到大
参考文章
https://www.cnblogs.com/clevercong/p/4198448.html
#include <bits/stdc++.h>
#define pb push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
const int N=12;
int data[N][N]={0},vis[N]={0};
int n,e;
void dfs(int a)
{
if(vis[a]) return ;
cout<<a<<" ";
vis[a]=1;
rep(i,0,N-1)
{
if(data[a][i]==1 && !vis[i]) dfs(i);
}
return ;
}
void bfs(int a)
{
if(vis[a]) return ;
queue<int> q;
q.push(a);
vis[a]=1;
while(!q.empty())
{
int x=q.front();
cout<<x<<" ";
q.pop();
rep(i,0,N-1)
{
if(data[x][i]==1 && !vis[i])
{
vis[i]=1;
q.push(i);
}
}
}
}
int main()
{
//freopen("D:\\LYJ.txt","r",stdin);
cin>>n>>e;
rep(i,0,e-1)
{
int a,b;
cin>>a>>b;
data[a][b]=1;
data[b][a]=1;
}
rep(i,0,n-1)
{
if(!vis[i])
{
cout<<"{ ";
dfs(i);
cout<<"}"<<endl;
}
}
mem(vis,0);
rep(i,0,n-1)
{
if(!vis[i])
{
cout<<"{ ";
bfs(i);
cout<<"}"<<endl;
}
}
return 0;
}