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 { 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 5
Sample Output:
{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 }
{ 6 }
#include<stdio.h> int N,E; int graph[20][20]={-1}; int visited[20]={0}; int queue[20]={-1}; void DFS(int v); void BFS(int v,int front,int rear); int main(void) { int v1,v2; int i=0; scanf("%d%d",&N,&E); for(i=0;i<E;i++){ scanf("%d%d",&v1,&v2); graph[v1][v2]=1; graph[v2][v1]=1; } for(i=0;i<N;i++){ if(visited[i]!=0) continue; else{ printf("{"); DFS(i); printf(" }\n"); } } for(i=0;i<N;i++) visited[i]=0; for(i=0;i<N;i++){ if(visited[i]!=0) continue; else{ visited[i]=1; queue[0]=i; printf("{"); BFS(i,0,1); printf(" }\n"); } } return 0; } void DFS(int v) { int w; visited[v]=1; printf(" %d",v); for(w=0;w<N;w++){ if(graph[v][w]==1){ if(visited[w]==0) DFS(w); } } } void BFS(int v,int front,int rear) { int w; while(1){ for(w=0;w<N;w++){ if(graph[v][w]==1){ if(visited[w]==0){ queue[rear++]=w; visited[w]=1; } } } printf(" %d",queue[front++]); if(front==rear) break; v=queue[front]; } }