알고리즘&자료구조/문제

[BOJ] 1260 DFS와 BFS C++

Nakuri 2023. 2. 2. 06:57
728x90

개요

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

실버 2급 DFS와 BFS 기초 문제다.

본문

풀이

인접 리스트 기반(vector)으로 구현했다.

각각 DFS는 stack, BFS는 queue를 사용했다.

정점의 번호가 작은 순으로 탐색하라는 조건이 있기 때문에 리스트(vector)를 정렬해주어야 한다.

DFS는 스택으로 후입선출이기 때문에 내림차순으로,

BFS는 큐로 선입선출이기 때문에 오름차순으로 정렬해주어야 한다.

 

코드

#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
constexpr int RANGE = 1002;

int N, M, V;
vector<int> graph[RANGE];

void dfs() 
{
	bool visit[RANGE]{};
	stack<int> s;
	s.push(V);


	for (int i = 1; i <= N; i++)
		sort(graph[i].rbegin(), graph[i].rend());

	while (!s.empty())
	{
		int v = s.top();
		s.pop();
		if (visit[v]) continue;
		
		visit[v] = true;
		cout << v << " ";

		for (int i = 0; i < graph[v].size(); i++)
			s.push(graph[v][i]);
	}
	cout << "\n";
}
void bfs()
{
	for (int i = 1; i <= N; i++)
		sort(graph[i].begin(), graph[i].end());

	bool visit[RANGE]{};
	queue<int> q;
	q.push(V);


	while (!q.empty())
	{
		int v = q.front();
		q.pop();
		if (visit[v]) continue;

		visit[v] = true;
		cout << v << " ";

		for (int i = 0; i < graph[v].size(); i++)
			q.push(graph[v][i]);
	}
	cout << "\n";
}

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

	cin >> N >> M >> V;

	for (int i = 1; i <= M; i++) {
		int from, to;
		cin >> from >> to;
		graph[from].push_back(to);
		graph[to].push_back(from);
	}

	dfs();
	bfs();
}

 

'알고리즘&자료구조 > 문제' 카테고리의 다른 글

[BOJ] 2178 미로탐색 C++  (0) 2023.02.03
[BOJ] 2644 촌수계산 C++  (0) 2023.02.03
[BOJ] 2309 일곱 난쟁이 C++  (0) 2023.02.02
[BOJ] 2606 바이러스 C++  (0) 2023.02.02
[BOJ] 2579 계단오르기 C++  (0) 2023.01.19