05-图1. List Components (25)
For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS and BFS. 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 "{ v1 v2 ... vk }". 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 5Sample Output:
{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 } { 6 }
1 #include<cstdio> 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<queue> 6 #include<vector> 7 #include<string> 8 using namespace std; 9 bool map[15][15]; 10 bool vis[15]; 11 queue<int> q; 12 int n,e; 13 void DFS(int a){ 14 q.push(a); 15 vis[a]=true; 16 int i; 17 for(i=0;i<n;i++){ 18 if(!vis[i]&&map[a][i]){ 19 DFS(i); 20 } 21 } 22 } 23 void BFS(int a){ 24 queue<int> qq; 25 qq.push(a); 26 q.push(a); 27 vis[a]=true; 28 int i; 29 while(!qq.empty()){ 30 a=qq.front(); 31 qq.pop(); 32 for(i=0;i<n;i++){ 33 if(!vis[i]&&map[a][i]){ 34 vis[i]=true; 35 q.push(i); 36 qq.push(i); 37 } 38 } 39 } 40 } 41 int main(){ 42 //freopen("D:\\INPUT.txt","r",stdin); 43 int a,b; 44 int i; 45 scanf("%d %d",&n,&e); 46 memset(map,false,sizeof(map)); 47 memset(vis,false,sizeof(vis)); 48 for(i=0;i<e;i++){ 49 scanf("%d %d",&a,&b); 50 map[a][b]=map[b][a]=true; 51 } 52 for(i=0;i<n;i++){ 53 if(!vis[i]){ 54 DFS(i); 55 if(!q.empty()){ 56 printf("{");//{ 0 1 4 2 7 } 57 while(!q.empty()){ 58 printf(" %d",q.front()); 59 q.pop(); 60 } 61 printf(" }\n"); 62 } 63 } 64 } 65 memset(vis,false,sizeof(vis)); 66 for(i=0;i<n;i++){ 67 if(!vis[i]){ 68 BFS(i); 69 if(!q.empty()){ 70 printf("{");//{ 0 1 4 2 7 } 71 while(!q.empty()){ 72 printf(" %d",q.front()); 73 q.pop(); 74 } 75 printf(" }\n"); 76 } 77 } 78 } 79 return 0; 80 }