-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path백준-DFS와 BFS.cpp.txt
87 lines (70 loc) · 1.05 KB
/
백준-DFS와 BFS.cpp.txt
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
#include<iostream>
#include<algorithm>
#include<math.h>
#include<vector>
#include<string>
#include<queue>
#include<map>
using namespace std;
int arr[1001][1001];
int N, M;
void dfs(bool visit[1001],int vertex)
{
cout << vertex << " ";
visit[vertex] = true;
for (int i = 0; i <= N; i++)
{
if (arr[vertex][i] == 1&&!visit[i])
{
dfs(visit, i);
}
}
}
int main()
{
int V;
bool visit[1001];
cin >> N >> M >> V;
for (int i = 0; i <= N; i++)
{
for (int j = 0; j <= N; j++)
{
arr[i][j] = 0;
}
}
for (int i = 0; i < M; i++)
{
int start, end;
cin >> start >> end;
arr[start][end] = 1;
arr[end][start] = 1;
}
for (int i = 0; i <= N; i++)
{
visit[i] = false;
}
dfs(visit,V);
cout << endl;
for (int i = 0; i <= N; i++)
{
visit[i] = false;
}
queue<int> q;
q.push(V);
visit[V] = true;
while (!q.empty())
{
int vertex = q.front();
q.pop();
cout << vertex << " ";
for (int i = 0; i <= N; i++)
{
if (arr[vertex][i] == 1 && !visit[i])
{
visit[i] = true;
q.push(i);
}
}
}
return 0;
}