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≤\le≤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 { v1v_1v1 v2v_2v2 ... vkv_kvk }. 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> #include<stdlib.h> #define MaxVertexNum 11 #define INFINITY 100000 struct GNode{ int GN; int GE; int G[MaxVertexNum][MaxVertexNum]; }; void DFS(int start, int visit[], struct GNode *Graph); int main(void) { struct GNode *Graph; int x,y,whether; Graph=(struct GNode*)malloc(sizeof(struct GNode)); scanf("%d %d",&Graph->GN,&Graph->GE); for(int i=0; i<MaxVertexNum; i++) { for(int j=0; j<MaxVertexNum; j++) { Graph->G[i][j]=INFINITY; } } for(int i=0; i<Graph->GE; i++) { scanf("%d %d",&x,&y); Graph->G[x][y]=1; Graph->G[y][x]=1; } int visit[Graph->GN]; for(int i=0; i<Graph->GN; i++) { visit[i]=0; } for(int i=0; i<Graph->GN; i++) { if(visit[i]==0) { printf("{ "); DFS(i,visit,Graph); printf("}\n"); } } for(int i=0; i<Graph->GN; i++) { visit[i]=0; } int Queue[Graph->GN][Graph->GN]; for(int i=0; i<Graph->GN; i++) { for(int j=0; j<Graph->GN; j++) { Queue[i][j]=-1; } } int front, rear; front=rear=0; int number=0; int now; for(int i=0; i<Graph->GN; i++) { if(visit[i]==0) { Queue[number][rear++]=i; visit[i]=1; while(front!=rear) { now=Queue[number][front++]; for(int j=0; j<Graph->GN; j++) { if(Graph->G[now][j]==1&&visit[j]==0) { Queue[number][rear++]=j; visit[j]=1; } } } number++; } } for(int i=0; i<number; i++) { printf("{ "); for(int j=0; j<Graph->GN; j++) { if(Queue[i][j]!=-1) { printf("%d ",Queue[i][j]); } } printf("}\n"); } } void DFS(int start, int visit[], struct GNode *Graph) { visit[start]=1; printf("%d ",start); for(int i=0; i<Graph->GN; i++) { if(Graph->G[start][i]==1&&visit[i]==0) DFS(i,visit,Graph); } }
贵校PTA作业,请自行绕道,以免不必要的麻烦