[BOJ/C++] 1260 DFS์™€ BFS

Hanbiยท2022๋…„ 9์›” 10์ผ
0

Problem Solving

๋ชฉ๋ก ๋ณด๊ธฐ
28/108
post-thumbnail

๋ฌธ์ œ

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

ํ’€์ด

DFS : Queue๋กœ ๊ตฌํ˜„
์ธ์ ‘๋ฆฌ์ŠคํŠธ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ DFS์™€ ๋™์ผ

์ธ์ ‘๋ฆฌ์ŠคํŠธ์— ์ ‘๊ทผํ•  ๋•Œ๋Š” ํ•ญ์ƒ for(int i=1; i<=N; i++)

์ฝ”๋“œ

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

vector<int> v[1001];
bool check[1001];

void dfs(int node) {
	check[node] = true;
	cout << node << " ";

	for (int i = 0; i < v[node].size(); i++) {
		int next = v[node][i];

		if (!check[next]) {
			dfs(next);
		}
	}

}

void bfs(int node) {
	queue<int> q;

	q.push(node);
	check[node] = true;

	while (!q.empty()) {
		int cur = q.front();

		q.pop();
		cout << cur << " ";
		
		for (int i = 0; i < v[cur].size(); i++) {
			int next = v[cur][i];

			if (!check[next]) {
				check[next] = true;
				q.push(next);
			}
		}
	}
}

int main() {
	int N, M, start;
	cin >> N >> M >> start;

	while(M--) {
		int v1, v2;
		cin >> v1 >> v2;

		v[v1].push_back(v2);
		v[v2].push_back(v1);
	}

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

	dfs(start);
	cout << '\n';
	fill_n(check, 1001, false);
	bfs(start);

	return 0;
}
profile
๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป

0๊ฐœ์˜ ๋Œ“๊ธ€