Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

hwooo

BOJ (C/C++) 24479번: 알고리즘 수업 - 깊이 우선 탐색 1 본문

Study/Algorithm

BOJ (C/C++) 24479번: 알고리즘 수업 - 깊이 우선 탐색 1

hwooo 2022. 12. 12. 06:42

풀이

입력 받고 각 노드를 오름차순으로 정렬한 후 DFS를 실행하였다. 방문한 기록이 없는 노드에만 DFS를 실행하고, cnt를 전역변수로 지정하여 DFS를 돌 때마다 값을 하나씩 증가시키며 방문 순서를 저장하였다.

코드

#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

vector <int> V[100001];
int visited[100001];
int N, M, R, cnt = 0;

void DFS(int R) {
	visited[R] = ++cnt;
	for (int i : V[R]) {
		if (!visited[i]) DFS(i);
	}
}

int main() {
	int a, b;

	// input
	scanf("%d %d %d", &N, &M, &R);
	for (int i = 0; i < M; i++) {
		scanf("%d %d", &a, &b);
		V[a].push_back(b);
		V[b].push_back(a);
	}

	// 오름차순 정렬
	for (int i = 1; i <= N; i++) {
		if (V[i].size() > 1)
			sort(V[i].begin(), V[i].end());
	}

	DFS(R);

	// print
	for (int i = 1; i <= N; i++)
		printf("%d\n", visited[i]);

	return 0;
}