Algorithm/C++

[백준] 1260번 : DFS와 BFS C++ 문제풀이 솔루션

Printemp 2024. 5. 16.

문제

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

입력

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

출력

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

 

DFS
BFS

 

DFS(깊이 우선 탐색), BFS(너비 우선 탐색) 알고리즘을 구현하는 문제이다.

DFS는 재귀 함수를 이용하여 구현하였고, BFS는 선입선출 방식의 queue를 이용하여 구현하였다.

이때, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문해야 하므로 인접 리스트를 오름차순으로 정렬해준다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <deque>

#define fast_io cin.tie(NULL); ios_base::sync_with_stdio(false)
using namespace std;

static vector<vector<int>> list;
static vector<bool> visited;

void dfs(int start, vector<int>& dfsresult) {
  sort(list[start].begin(), list[start].end()); //정점 번호가 작은 것을 먼저 방문
  if (!visited[start]) {
	visited[start] = true;
	dfsresult.push_back(start);
  } else return;
  for (int i : list[start]) {
	dfs(i, dfsresult);
  }
}
void bfs(int start, vector<int>& bfsresult) {
  deque<int> bfslist;
  bfslist.push_back(start);
  bfsresult.push_back(start);
  visited[start] = true;
  while (true) {
	for (int j : list[bfslist.front()]) {
	  if (!visited[j]) {
		visited[j] = true;
		bfsresult.push_back(j);
		bfslist.push_back(j);
	  }
	  if (bfslist.empty()) break;
	}
	bfslist.pop_front();
	if (bfslist.empty()) break;
  }
}
int main() {
  fast_io;
  int n, m, v;
  cin >> n >> m >> v;
  list = vector<vector<int>>(n);
  visited = vector<bool>(n, false);
  vector<int> dfsresult;
  vector<int> bfsresult;
  for (int i = 0; i < m; i++) { //인접 리스트 생성
	int a, b;
	cin >> a >> b;
	list[a - 1].push_back(b - 1);
	list[b - 1].push_back(a - 1);
  }
  dfs(v - 1, dfsresult);
  fill(visited.begin(), visited.end(), false); //방문 기록 배열 초기화
  bfs(v - 1, bfsresult);
  for (int i : dfsresult) cout << i + 1 << ' ';
  cout << '\n';
  for (int i : bfsresult) cout << i + 1 << ' ';
  return 0;
}

댓글

💲 추천 글