본문 바로가기
알고리즘

BOJ 1260 DFS와 BFS

by LaTale 2018. 10. 4.

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 


단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 


정점 번호는 1번부터 N번까지이다.





DFS, BFS도 뭐.. 그냥 개념이니깐 적당히 짜면 된다.


DFS는 재귀를 이용하고 BFS는 큐를 이용하면 된다.


 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 1260 DFS와 BFS
#include<stdio.h>
#define MAX 1002
#define FOR(i,j) for(int i=1;i<=j;i++)
void DFS(int v);
void BFS(int v);
void queue_push(int X);
int queue_pop();
int queue_empty();
int adj[MAX][MAX];
int N, front, back;
int queue[MAX], visit[MAX];
int main() {
	int M, V, v, w;
	scanf("%d %d %d", &N, &M, &V);
	while (M--) {
		scanf("%d %d", &v, &w);
		adj[v][w] = 1;
		adj[w][v] = 1;
	}
	DFS(V);
	printf("\n");
	BFS(V);
	return 0;
}
void DFS(int v) {
	int w;
	visit[v] = 1;
	printf("%d ", v);
	FOR(w, N) {
		if (adj[v][w] && !visit[w])
			DFS(w);
	}
}
void BFS(int v) {
	int w;
	int visited[MAX] = { 0, };
	visited[v] = 1;
	printf("%d ", v);
	queue_push(v);
	while (!queue_empty()) {
		v = queue_pop();
		FOR(w, N) {
			if (adj[v][w] && !visited[w]) {
				visited[w] = 1;
				printf("%d ", w);
				queue_push(w);
			}
		}
	}
}
void queue_push(int X) {
	queue[back] = X;
	back++;
}
int queue_pop() {
	if (front == back)
		return -1;
	return queue[front++];
}
int queue_empty() {
	if (front == back)
		return 1;
	return 0;
}




'알고리즘' 카테고리의 다른 글

BOJ 11866 조세퍼스 문제0  (0) 2018.10.04
BOJ 1966 프린터 큐  (0) 2018.10.04
BOJ 10845 큐  (0) 2018.10.04
BOJ 2504 괄호의 값  (0) 2018.10.04
BOJ 9012 괄호  (0) 2018.09.01