PAT List Components

List Components

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.

 

给定 顶点数N 边数E 以及 顶点的连通关系

分别求DFS和BFS 的遍历

 1 #include "stdio.h"

 2 

 3 int flag[10];

 4 int graph[10][10];

 5 int v,e;

 6 void DFS(int i)

 7 {

 8     int j;

 9     printf("%d ",i);

10     flag[i]=1;

11     for(j=0;j<v;j++)

12     {

13         if(graph[i][j]==1 && flag[j]!=1)

14             DFS(j);

15     }

16 }

17 void BFS(int i)

18 {

19     int start,end,q[10],temp,j;

20     start=end=0;

21     q[end++]=i;

22     flag[i]=1;

23     while(start<end)

24     {

25         temp=q[start];

26         start++;

27         printf("%d ",temp);

28         for(j=0;j<v;j++)

29         {

30             if(graph[temp][j]==1 && flag[j]!=1)

31             {

32                 q[end++]=j;

33                 flag[j]=1;

34             }

35         }

36     }

37     

38 }

39 main()

40 {

41     int i,m,n;

42     scanf("%d%d",&v,&e);

43     for(i=0;i<e;i++)

44     {

45         scanf("%d%d",&m,&n);

46         graph[m][n]=graph[n][m]=1;

47     }

48     for(i=0;i<v;i++)

49     {

50         if(flag[i]==1)

51             continue;

52         else

53         {    

54             printf("{ ");

55             DFS(i);    

56             printf("}\n");    

57         }

58     }

59     for(i=0;i<v;i++)

60         flag[i]=0;

61     for(i=0;i<v;i++)

62     {

63         if(flag[i]==1)

64             continue;

65         else

66         {    

67             printf("{ ");

68             BFS(i);    

69             printf("}\n");    

70         }

71     }

72 }

 

你可能感兴趣的:(component)