-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS기본,DFS기본.cpp
129 lines (99 loc) · 1.97 KB
/
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/***************
1
/ \
2 ------3
/ \ / \
4---5 6---7
이런 모양의 이진 트리가 있다고 가정했을 때의 bfs
****************/
/***************
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int number=4;
bool c[4]; //방문했는지 체크하는 배열
vector<int> a[5]; //첫 인덱스의 시작이 0이 아닌 1로 하기 위해서 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;
}
}
}
}
int main()
{
a[1].push_back(2);
a[2].push_back(1);
a[1].push_back(3);
a[3].push_back(1);
a[1].push_back(4);
a[4].push_back(1);
a[2].push_back(4);
a[4].push_back(2);
a[2].push_back(5);
a[5].push_back(2);
a[3].push_back(6);
a[6].push_back(3);
a[3].push_back(7);
a[7].push_back(3);
a[4].push_back(5);
a[5].push_back(4);
a[6].push_back(7);
a[7].push_back(6);
bfs(1);
}
**********************/
#include <iostream>
#include <vector>
using namespace std;
int number=7;
bool c[7];
vector<int> a[8];
void dfs(int x)
{
if(c[x]) return;
c[x]=true;
cout<<x<<" ";
for(int i=0;i<a[x].size();i++)
{
int y=a[x][i];
dfs(y);
}
}
int main()
{
a[1].push_back(2);
a[2].push_back(1);
a[1].push_back(3);
a[3].push_back(1);
a[1].push_back(4);
a[4].push_back(1);
a[2].push_back(4);
a[4].push_back(2);
a[2].push_back(5);
a[5].push_back(2);
a[3].push_back(6);
a[6].push_back(3);
a[3].push_back(7);
a[7].push_back(3);
a[4].push_back(5);
a[5].push_back(4);
a[6].push_back(7);
a[7].push_back(6);
dfs(1);
}