-
[BOJ-1260] DFS와 BFS 본문
https://www.acmicpc.net/problem/1260
BFS와 DFS 완전탐색에 대한 그래프 문제다.
BFS/DFS에 대한 개념을 잡게해주는 문제였다. 깊이우선 탐색과 너비우선 탐색. 각각의 성격에 대해 통찰을 얻을 수 있었다.
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#define maxVirtex 1000+1
using namespace std;
vector Adj[maxVirtex];
bool check[maxVirtex];
void falsing(){
for(int i=0; i<maxVirtex; i++)
check[i] = false;
}
void dfs(int start){
cout << start << " ";
check[start] = true;
for(int i=0; i<Adj[start].size(); i++){
int curSearch = Adj[start][i];
if(!check[curSearch]){
check[curSearch] = true;
dfs(curSearch);
}
}
}
void bfs(int start){
queue q;
check[start] = true;
q.push(start);
while(!q.empty()){
int front = q.front();
q.pop();
cout << front << " ";
for(int i=0; i<Adj[front].size(); i++){
int y = Adj[front][i];
if(!check[y]){
check[y] = true;
q.push(y);
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int N, M, V;
int a, b;
cin >> N >> M >> V;
for(int i=0; i<M; i++){
cin >> a >> b;
Adj[a].push_back(b);
Adj[b].push_back(a);
}
for(int i=1; i<maxVirtex; i++)
sort(Adj[i].begin(), Adj[i].end());
falsing();
dfs(V);
cout << '\n';
falsing();
bfs(V);
cout << '\n';
return 0;
}
'3. DFS & 백트래킹' 카테고리의 다른 글
[DFS] 백준 2468번 - 안전영역 (정답률 33%) (0) | 2020.01.13 |
---|---|
[DFS] 백준 2583번 - 영역 구하기 (정답률 56%) (0) | 2020.01.13 |
[DFS] 백준 2667번 - 단지번호붙이기 (정답률 38%) (0) | 2020.01.07 |
[DFS] 백준 1012번 - 유기농 배추 (정답률 34%) (0) | 2020.01.07 |
[DFS] 백준 11403번 - 경로 찾기 (정답률 51%) (0) | 2020.01.07 |