문제 링크


🔷 분류

그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색

✒️ 문제 설명

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

⬅️ 입력

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

➡️ 출력

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

💻 코드 (C++)

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

void dfs(int v, const vector<vector<int>>& arr, vector<bool>& visit, vector<int>& dfs_res) {
	for (int i = 0; i < arr[v].size(); i++) {
		int next = arr[v][i];
		if (!visit[next]) {
			visit[next] = true;
			dfs_res.push_back(next);
			dfs(next, arr, visit, dfs_res);
		}
	}
}

void bfs(int v, const vector<vector<int>>& arr, vector<bool>& visit, vector<int>& bfs_res) {
	queue<int> q;
	q.push(v);
	visit[v] = true;

	while (!q.empty()) {
		int curr = q.front(); q.pop();
		bfs_res.push_back(curr);

		for (int i = 0; i < arr[curr].size(); i++) {
			int next = arr[curr][i];
			if (!visit[next]) {
				visit[next] = true;
				q.push(next);
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int n, m, v;
	cin >> n >> m >> v;

	vector<vector<int>> adj(n + 1);
	vector<bool> dfs_visit(n + 1, false);
	vector<bool> bfs_visit(n + 1, false);
	vector<int> dfs_result;
	vector<int> bfs_result;

	for (int i = 0; i < m; i++) {
		int a, b;
		cin >> a >> b;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}

	for (int i = 1; i <= n; i++) {
		sort(adj[i].begin(), adj[i].end());
	}

	// DFS
	dfs_visit[v] = true;
	dfs_result.push_back(v);
	dfs(v, adj, dfs_visit, dfs_result);
	for (auto n : dfs_result) cout << n << " ";
	cout << "\n";

	// BFS
	bfs(v, adj, bfs_visit, bfs_result);
	for (auto n : bfs_result) cout << n << " ";
	cout << "\n";

	return 0;
}

글 이동

Comments