[BOJ] 1260 DFS와 BFS

Time Lapse :None

1260.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
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <queue>
using namespace std;

int map[1001][1001];
bool visit[1001];
int N,M,V;
vector<int> BFS_ans;
vector<int> DFS_ans;
queue<int> q;
void DFS(int v)
{
if(visit[v])
return;
DFS_ans.push_back(v);
visit[v]=true;
for(int i=1;i<=N;i++)
{
if(map[v][i]!=-1)
DFS(i);
}
}
void BFS(int v)
{
if(visit[v])
return;
BFS_ans.push_back(v);
visit[v]=true;
for(int i=1;i<=N;i++)
{
if(map[v][i]!=-1&&!visit[i])
{
q.push(i);
}
}
while(!q.empty())
{
int tq = q.front();
q.pop();
BFS(tq);
}
}

int main(void)
{
memset(map,-1,sizeof(map));
cin>>N>>M>>V;
for(int i=0;i<M;i++)
{
int n,m;
cin>>n>>m;
map[n][m]=1;
map[m][n]=1;
}
memset(visit,false,sizeof(visit));
DFS(V);
memset(visit,false,sizeof(visit));
q.push(V);
BFS(V);
for(int i=0;i<DFS_ans.size();i++)
cout<<DFS_ans[i]<<" ";
cout<<endl;
for(int i=0;i<BFS_ans.size();i++)
cout<<BFS_ans[i]<<" ";
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/23/PS/BOJ/1260/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.