列出连通集

06-图1 列出连通集(25 分)

给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入格式:

输入第1行给出2个整数N(0<N10)和E,分别是图的顶点数和边数。随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。

输出格式:

按照"{ v1​​ v2​​ ... vk​​ }"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。

输入样例:

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 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 using namespace std;
 5 #define maxvertexnum 10 
 6 #define weighttype int
 7 #define datatype string
 8 #define vertex int
 9 struct graph{
10 int Nv;//定点数 
11 int Ne;//边数
12 weighttype G[maxvertexnum][maxvertexnum];
13 datatype data[maxvertexnum];
14 };
15 using Graph=graph*;
16 vector<int> visited(maxvertexnum,0);
17 queue<int> q;
18 struct Enode{
19 vertex v1,v2;
20 weighttype weight;
21 };
22 using edge=Enode*;
23 Graph creategraph(int vertexnum){
24 int w,v; Graph gra=new graph();
25 gra->Nv=vertexnum;
26 gra->Ne=0;
27 for(v=0;v<gra->Nv;v++)
28 for(w=0;w<gra->Nv;w++)
29 gra->G[v][w]=0;
30 return gra;
31 }
32 void Insert(Graph gra,edge e){
33 gra->G[e->v1][e->v2]=1;
34 gra->G[e->v2][e->v1]=1;
35 }
36 Graph buildgraph(){
37 Graph gra; edge e; vertex v;int Nv,i;
38 cin>>Nv;
39 gra=creategraph(Nv);
40 cin>>gra->Ne;
41 if(gra->Ne){
42 e=new Enode();
43 for(i=0;i<gra->Ne;i++){
44 cin>>e->v1>>e->v2;
45     Insert(gra,e);} 
46 }
47    //for(v=0;v<gra->Nv;v++)
48    //cin>>gra->data[v];
49    return gra;
50 }
51 void DFS(Graph gra,vertex v)
52 {   vertex v1;
53 cout<<v<<" "; visited[v]=1;
54 for(v1=0;v1<gra->Nv;v1++)
55 if(gra->G[v][v1]==1&&visited[v1]!=1)
56 DFS(gra,v1);
57 }
58 void BFS(Graph gra)
59 {   vertex v1,v2;
60 if(q.size()!=0){ 
61     v1=q.front();
62 q.pop();
63 if(visited[v1]!=1){cout<<v1<<" "; visited[v1]=1;}
64 for(v2=0;v2<gra->Nv;v2++){
65 if(visited[v2]!=1&&gra->G[v1][v2]==1)
66 q.push(v2);}
67 BFS(gra);}  
68 }
69 void DFSLOOK(Graph gra){
70 vertex v;
71 for(v=0;v<gra->Nv;v++){
72 if(visited[v]!=1){
73 cout<<"{ ";  DFS(gra,v); cout<<"}"<<endl;
74 }
75 }
76 for(auto &o:visited)
77 o=0;
78 }
79 void BFSLOOK(Graph gra){
80 vertex v;
81 for(v=0;v<gra->Nv;v++){
82 if(visited[v]!=1){
83 cout<<"{ ";  q.push(v); BFS(gra); cout<<"}"<<endl;
84 }
85 }
86     for(auto &o:visited)
87 o=0; 
88 }
89 int main(){
90 Graph gra=buildgraph();
91 //for(int i=0;i<gra->Nv;i++)
92 //for(int j=0;j<gra->Nv;j++)
93 //cout<<gra->G[i][j]<<" "<<endl;
94 DFSLOOK(gra);
95 BFSLOOK(gra);
96 return 0;
97 }
View Code

 

 
posted @ 2017-12-18 09:26  A-Little-Nut  阅读(389)  评论(0编辑  收藏  举报