그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
DFS BFS를 차례대로 해주면 된다.DFS를 먼저해서 DFS 함수 내에서 정렬을 해주면 BFS에서 정렬을 안해줘도 되지 않을까 싶었지만 main에서 하는 방식으로 변경했다.DFS 끝나고 한 줄 안 띄어서 출력 형식 오류가 났다.#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<int> graph[1001];
bool dfsArr[1001] = {0, };
bool bfsArr[1001] = {0, };
void dfs(int n) {
dfsArr[n] = true;
cout<<n<<" ";
for(int i=0; i<graph[n].size(); ++i) {
if(dfsArr[graph[n][i]]) continue;
dfs(graph[n][i]);
}
}
void bfs(int n) {
bfsArr[n] = true;
queue<int> q;
q.push(n);
while(!q.empty()) {
int vertex = q.front();
q.pop();
cout<<vertex<<" ";
for(int i=0; i<graph[vertex].size(); ++i) {
int next = graph[vertex][i];
if(bfsArr[next]) continue;
bfsArr[next] = true;
q.push(next);
}
}
}
int main(){
int numberOfVertex, numberOfEdge, startVertex;
cin >> numberOfVertex >> numberOfEdge >> startVertex;
for (int i = 0; i < numberOfEdge; ++i) {
int n, m;
cin>>n>>m;
graph[n].push_back(m);
graph[m].push_back(n);
}
for(int i=1; i<=numberOfVertex; ++i) {
sort(graph[i].begin(), graph[i].end());
}
dfs(startVertex);
cout<<endl;
bfs(startVertex);
}