-
Notifications
You must be signed in to change notification settings - Fork 1
/
05-1 List Components (25).cpp
87 lines (86 loc) · 1.14 KB
/
05-1 List Components (25).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <vector>
#include <queue>
#define MAX 12
using namespace std;
int vis[MAX];
int m[MAX][MAX];
int n,e;
vector<int> path;
queue<int> q;
void _print()
{
cout<<"{ "<<path[0];
for(int j=1;j<path.size();j++)
{
cout<<' '<<path[j];
}
cout<<" }"<<endl;
path.clear();
}
void DFS(int v)
{
vis[v]=1;
path.push_back(v);
for(int i=0;i<n;i++)
{
if(!vis[i]&&m[v][i])
{
DFS(i);
}
}
}
void BFS(int v)
{
int tmp;
vis[v]=1;
path.push_back(v);
q.push(v);
while(!q.empty())
{
tmp=q.front();
for(int i=0;i<n;i++)
{
if(!vis[i]&&m[tmp][i])
{
BFS(i);
}
}
if(!q.empty()) q.pop();
}
if(path.size()) _print();
}
int main()
{
cin>>n>>e;
for(int i=0;i<n;i++) vis[i]=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
m[i][j]=0;
}
}
for(int i=0;i<e;i++)
{
int tmp1,tmp2;
cin>>tmp1>>tmp2;
m[tmp1][tmp2]=1;
m[tmp2][tmp1]=1;
}
for(int i=0;i<n;i++)
{
if(path.size()) _print();
if(!vis[i]) DFS(i);
}
if(path.size()) _print();
for(int i=0;i<n;i++) vis[i]=0;
for(int i=0;i<n;i++)
{
if(path.size()) _print();
if(!vis[i]) BFS(i);
}
if(path.size()) _print();
system("PAUSE");
return 0;
}