-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260_acm(BFS&DFS).cpp
108 lines (75 loc) · 1.38 KB
/
1260_acm(BFS&DFS).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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
#include <vector>
#include <memory.h>
#include <queue>
#include <algorithm>
using namespace std;
bool check[1001] = {false};
vector<int> v[1001];
void dfs(int x){
if(check[x]==false){
check[x]=true;
cout<<x<<' ';
}
if(v[x].size()==0){
return;
}
for(int i=0;i<v[x].size();i++){
int y=v[x][i];
if(check[y]==false){
dfs(y);
}
}
}
void bfs(int x){
queue<int> q;
memset(check,0,sizeof(check));
check[x]=true;
q.push(x);
while(!q.empty()){
int node = q.front();
q.pop();
cout<<node<<' ';
for(int i=0;i<v[node].size();i++){
if(check[v[node][i]]==false){
check[v[node][i]]=true;
//cout<<v[node][i]<<' ';
q.push(v[node][i]);
}
}
}
}
int main(){
int N;
int M;
int V;
int data1;
int data2;
cin>>N>>M>>V;
int **yes = new int*[N+1];
for(int i=1;i<=N;i++){
yes[i]=new int[N+1];
}
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
yes[i][j]=0;
}
}
for(int i=0;i<M;i++){
cin>>data1>>data2;
if(yes[data1][data2]!=1){
v[data1].push_back(data2);
v[data2].push_back(data1);
yes[data1][data2]=1;
yes[data2][data1]=1;
}
}
for(int i=1;i<=N;i++){
sort(v[i].begin(),v[i].end());
}
dfs(V);
cout<<'\n';
bfs(V);
cout<<'\n';
return 0;
}