그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
void dfs(int start, vector<int> graph[], bool check[]) {
check[start] = true;
cout << start << " ";
for (int i = 0; i < graph[start].size(); i++) {
int next = graph[start][i];
if (check[next] == false) {
dfs(next, graph, check);
}
}
}
void bfs(int start, vector<int> graph[], bool check[]) {
queue<int> q;
q.push(start);
check[start] = true;
while (!q.empty()) {
int tmp = q.front();
q.pop();
cout << tmp << " ";
for (int i = 0; i < graph[tmp].size(); i++) {
int next = graph[tmp][i];
if (check[next] == false) {
q.push(next);
check[next] = true;
}
}
}
}
int main(void) {
cin.tie(NULL); ios::sync_with_stdio(false);
int N, M, start;
int n1, n2;
bool* check;
cin >> N >> M >> start;
vector<int>* graph= new vector<int>[N + 1];
check = new bool[N + 1];
fill(check, check + N + 1, false);
for (int i = 0; i < M; i++) {
cin >> n1 >> n2;
graph[n1].push_back(n2);
graph[n2].push_back(n1);
}
for (int i = 1; i < N + 1; i++) {
sort(graph[i].begin(), graph[i].end());
}
dfs(start, graph, check);
cout << "\n";
fill(check, check + N + 1, false);
bfs(start, graph, check);
return 0;
}
+> https://twpower.github.io/73-how-to-implement-dfs-and-bfs-in-cpp