https://www.acmicpc.net/problem/1260
이 문제는 DFS의 탐색 결과와 BFS의 탐색 결과를 출력하면 된다.
#include <iostream>
#include <vector>
#include <queue>
#include<algorithm>
using namespace std;
int graph[1001][1001] = {0, };
int N, M, V;
int visited[1001] = {0,};
vector<int> stack;
queue<int> q;
void DFS(){
stack.push_back(V);
while(!stack.empty()){
int p = stack.back();
stack.pop_back();
if(visited[p]) continue;
visited[p] = 1;
cout<<p<<' ';
for(int next = N; next >= 1; next--){
if(!visited[next] && graph[p][next])
stack.push_back(next);
}
}
cout<<'\n';
}
void init(){
for(int i = 0;i<1001;i++){
visited[i] = 0;
}
}
void BFS(){
q.push(V);
while(!q.empty()){
int p = q.front();
q.pop();
if(visited[p]) continue;
visited[p] = 1;
cout<<p<<' ';
for(int next = 1; next <= N; next++){
if(!visited[next] && graph[p][next])
q.push(next);
}
}
cout<<'\n';
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>N>>M>>V;
for(int i = 0;i<M;i++){
int p, e;
cin>>p>>e;
graph[p][e] = 1;
graph[e][p] = 1;
}
DFS();
init();
BFS();
}
BFS와 DFS의 자세한 설명은 아래를 참고하면 된다.
https://hanseongbugi2study.tistory.com/37
https://hanseongbugi2study.tistory.com/36
'Baekjoon Review' 카테고리의 다른 글
[Silver 1] 1389번 케빈 베이컨의 6단계 법칙 (0) | 2023.10.25 |
---|---|
[Gold 5] 1107번 리모컨 (0) | 2023.10.24 |
[Silver 1] 1074번 Z (0) | 2023.10.23 |
[Silver 2] 1012번 유기농 배추 (0) | 2023.10.20 |
[Silver 3] 1003번 피보나치 함수 (0) | 2023.10.19 |