본문 바로가기
알고리즘/BOJ(백준)

[ 백준-1260번 / DFS/BFS ] DFS와 BFS

by 뎁꼼 2020. 3. 8.

1. 문제


DFS와 BFS 성공

시간 제한메모리 제한제출정답맞은 사람정답 비율

2 초 128 MB 86663 28430 16542 31.467%

문제

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

입력

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

출력

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

예제 입력 1 복사

4 5 1 1 2 1 3 1 4 2 4 3 4

예제 출력 1 복사

1 2 4 3 1 2 3 4

예제 입력 2 복사

5 5 3 5 4 5 2 1 2 3 4 3 1

예제 출력 2 복사

3 1 2 5 4 3 1 4 2 5

예제 입력 3 복사

1000 1 1000 999 1000

예제 출력 3 복사

1000 999 1000 999

 

 

 

2. 소스코드


#include <iostream>
#include <vector>
#include <queue>
#include <cstring> // for memset
#include <algorithm>

using namespace std;

vector<int> adjList[1000];
bool visited[1000];

void dfs(int v) {
	visited[v] = true;
	for (int i = 0; i < adjList[v].size(); i++) {
		int next = adjList[v][i];
		if (!visited[next]) {
			//cout << next << " ";
			cout << next + 1 << " ";
			dfs(next);
		}
	}
}

int main() {

	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);

	int n, m, v;

	cin >> n >> m >> v;

	for (int i = 0; i < m; i++) {
		int from, to;
		cin >> from >> to;
		from--; to--;
		adjList[from].push_back(to);
		adjList[to].push_back(from);
	}
	for (int i = 0; i < n; i++) {
		sort(adjList[i].begin(), adjList[i].end());
	}

	cout << v << " ";
	//dfs(1);
	dfs(v - 1);
	cout << '\n';

	memset(visited, false, sizeof(visited));

	queue <int> q;
	q.push(v - 1); visited[v - 1] = true;
	//cout << v << " ";
	while (!q.empty())
	{
		int v = q.front(); q.pop();
		cout << v + 1 << " ";
		for (int i = 0; i < adjList[v].size(); i++) {
			int next = adjList[v][i];
			if (!visited[next]) {
				q.push(next); visited[next] = true;
				//cout << next + 1 << " ";
			}
		}
	}
	return 0;
}