# 06-图1 列出连通集

### 输入样例:

8 6
0 7
0 1
2 0
4 1
2 4
3 5


### 输出样例:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }
 1 /* 图的邻接矩阵表示简化法*/
2 #include <iostream>
3 #include <cstdio>
4 #include <queue>
5 using namespace std;
6
7 #define MaxSize 10
8
9 int graph[MaxSize][MaxSize], Nv, Ne;//Nv顶点数 Ne边数
10 int check[MaxSize];
11 void buildGraph()
12 {
13     int v1,v2;
14     scanf("%d %d",&Nv, &Ne);
15     for(int i = 0; i < Nv; i++){
16         check[i] = 0;
17         for(int j = 0; j < Ne; j++)
18             graph[i][j] = 0;
19     }
20
21     for(int i = 0; i < Ne; i++) {
22         scanf("%d %d",&v1, &v2);
23         graph[v1][v2] = 1;    //1有边
24         graph[v2][v1] = 1;
25     }
26 }
27 int checkVisited()
28 {
29     int i;
30     for(i = 0; i < Nv; i ++){
31         if( !check[i] )
32             break;
33     }
34     if(i == Nv)    //如果都被访问了
35         return -1;
36     return i;
37 }
38
39 void clearCheck()
40 {
41     for(int i = 0; i < Nv; i++)
42         check[i] = 0;
43 }
44
45 int BFS()
46 {
47     queue<int> queue;
48     int i,j;
49     i = checkVisited();
50     if( i == -1 )
51         return -1;
52     queue.push(i);
53     check[i] = 1;//该顶点已访问
54     printf("{ %d ",i);
55     while( !queue.empty() ) {
56         int tempi = queue.front();
57         queue.pop();
58         for(j = 0; j < Nv; j++)
59             if(graph[tempi][j] == 1 && !check[j]) {
60                 check[j] = 1;//该顶点已访问
61                 printf("%d ",j);
62                 queue.push(j);
63             }
64     }
65     printf("}\n");
66     return BFS();
67 }
68
69 void DFS(int Vi)
70 {
71     check[Vi] = 1;
72     printf("%d ",Vi);
73     for(int j = 0; j < Nv; j++) {
74         if(graph[Vi][j] == 1 && !check[j])
75             DFS(j);
76     }
77 }
78 int listDFS()
79 {
80     if( checkVisited() == -1 )
81         return -1;
82     printf("{ ");
83     DFS( checkVisited() );
84     printf("}\n");
85     return listDFS();
86 }
87 int main()
88 {
89     buildGraph();
90     listDFS();
91     clearCheck();
92     BFS();
93     return 0;
94 }

posted on 2016-04-09 11:01  kuotian  阅读(343)  评论(0编辑  收藏  举报