안녕 세상아,

[백준/c++] 1260 DFS와 BFS 본문

백준

[백준/c++] 1260 DFS와 BFS

돈 많은 백수가 되고싶다 2025. 1. 21. 01:02

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

 

BFS와 DFS의 기본적인 문제이다. 템플릿으로 사용해도 될듯..

값을 입력할 때 양방향 간선으로 고려해야한다. 또한, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문 한다는 조건을 생각해서 정렬한다. 

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

int n, m, v;
bool isVisited[1001] = { false };
vector<int> graph[1001];

void reset() {
	for (int i = 1; i <= n; i++) {
		isVisited[i] = false;
	}
}

void bfs(int start) {
	queue<int> q;
	q.push(start);
	isVisited[start] = true;
	
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		cout << x << " ";
		for (int i = 0; i < graph[x].size(); i++) {
			int y = graph[x][i];
			if (!isVisited[y]) {
				isVisited[y] = true;
				q.push(y);
			}
		}
	}
}

void dfs(int x) {
	isVisited[x] = true;
	cout << x << " ";
	for (int i = 0; i < graph[x].size(); i++) {
		int y = graph[x][i];
		if (!isVisited[y]) {
			dfs(y);
		}
	}
}

int main() {
	cin >> n >> m >> v;

	for (int i = 0; i < m; i++) {
		int a, b;
		cin >> a >> b;
		graph[a].push_back(b);
		graph[b].push_back(a);
	}
	for (int i = 1; i <= n; i++) {
		sort(graph[i].begin(), graph[i].end());
	}
	dfs(v);
	cout << endl;

	reset();
	bfs(v);
}

'백준' 카테고리의 다른 글

[백준/c++] 1654 랜선 자르기  (0) 2025.01.18
[백준/c++] 2776 암기왕  (1) 2025.01.13
[백준/c++] 1436 영화감독  (0) 2025.01.08
[백준/c++] 10814 나이순 정렬  (1) 2025.01.06
[백준/c++] 분수 찾기  (0) 2025.01.02