알고리즘/[문제풀이] 백준
[백준] 1260 DFS와 BFS
로그뉴
2020. 1. 9. 17:26
문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
출력
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
// 인접리스트, 스택으로 구현
void dfs(int start, vector<vector<int>> graph, vector<bool> check) {
stack<int> s;
int current_node, next_node;
s.push(start);
check[start] = true;
printf("%d ", start);
while (!s.empty()) { // stack이 비어 있을 때까지 반복
current_node = s.top();
s.pop();
for (int i = 0; i < graph[current_node].size(); i++) {
next_node = graph[current_node][i];
if (!check[next_node]) { // 아직 방문하지 않은 노드라면..
printf("%d ", next_node);
check[next_node] = true; // 방문 완료 표시
s.push(current_node);
s.push(next_node);
break; // dfs를 진행하기 위함
}
}
}
}
void bfs(int start, vector<vector<int>> graph, vector<bool> check) {
queue<int> q;
int current_node, next_node;
q.push(start);
check[start] = true;
while (!q.empty()) { // queue가 비어 있을 때까지 반복
current_node = q.front();
q.pop();
printf("%d ", current_node);
for (int i = 0; i < graph[current_node].size(); i++) {
int tmp = graph[current_node][i];
if (!check[tmp]) { // 아직 방문하지 않은 노드라면..
check[tmp] = true; // 방문 완료 표시
q.push(tmp);
}
}
}
}
int main() {
int N, M, start;
int u, v;
vector<vector<int>> graph;
vector<bool> check;
cin >> N >> M >> start;
graph.resize(N + 1);
check.resize(N + 1);
for (int i = 0; i < M; i++) {
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
for (int i = 1; i <= N; i++) {
sort(graph[i].begin(), graph[i].end());
}
dfs(start, graph, check);
printf("\n");
bfs(start, graph, check);
return 0;
}