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
|
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
int number = 7;
bool c[7];
vector<int> a[8];
void bfs(int start) {
queue<int> q;
q.push(start);
c[start] = true;
while (!q.empty()) {
int x = q.front();
q.pop();
cout << x << ' ';
for (int i = 0; i < a[x].size(); i++) {
int y = a[x][i];
if (!c[y]) {
q.push(y);
c[y] = true;
}
}
}
}
void dfs(int start) {
if (c[start]) return;
c[start] = true;
cout << start << ' ';
for (int i = 0; i < a[start].size(); i++) {
int y = a[start][i];
dfs(y);
}
}
void linkEdge(int x, int y) {
a[x].push_back(y);
a[y].push_back(x);
}
int main() {
linkEdge(1, 2);
linkEdge(1, 3);
linkEdge(2, 3);
linkEdge(2, 4);
linkEdge(2, 5);
linkEdge(4, 5);
linkEdge(3, 6);
linkEdge(3, 7);
linkEdge(6, 7);
dfs(1);
return 0;
}
|
cs |
bfs 출력 결과 :
1 2 3 4 5 6 7
dfs 출력 결과 :
1 2 3 6 7 4 5
'C,C++ > Algorithm' 카테고리의 다른 글
Algorithm, c++, Heap sort (0) | 2019.09.23 |
---|---|
Algorithm, c++, Sort (0) | 2019.09.23 |