BOJ[백준] - 1260 - DFS와 BFS
https://www.acmicpc.net/problem/1260
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87 |
#include <cstdio>
#define MAXNUM 1001
int N, M, head, tail;
int queue[MAXNUM];
int graph[MAXNUM][MAXNUM];
int isVisited[MAXNUM];
int isEmpty()
{
return (head == tail);
}
void enqueue(int n)
{
queue[head++] = n;
head = head % MAXNUM;
}
int dequeue()
{
int ret;
if(isEmpty())
return -1;
else
{
ret = queue[tail++];
tail = tail % MAXNUM;
return ret;
}
}
void DFS(int v)
{
int i;
if(isVisited[v])
return;
printf("%d ", v);
isVisited[v] = true;
for(i = 1; i <= N; i++)
if(graph[v][i])
DFS(i);
}
void BFS(int v)
{
int i, val;
enqueue(v);
isVisited[v] = true;
while(!isEmpty())
{
val = dequeue();
printf("%d ", val);
for(i = 1; i <= N; i++)
{
if(graph[val][i] && !isVisited[i])
{
enqueue(i);
isVisited[i] = true;
}
}
}
}
int main()
{
int V, v1, v2, i;
scanf("%d %d %d", &N, &M, &V);
while(M--)
{
scanf("%d %d", &v1, &v2);
graph[v1][v2] = graph[v2][v1] = 1; // adjacent matrix
}
DFS(V);
// initialization
for(i = 1; i <= N; i++)
isVisited[i] = false;
printf("\n");
BFS(V);
} |
cs |
'Algorithm 문제풀이 > BOJ [백준] 문제풀이' 카테고리의 다른 글
BOJ[백준] - 10026 - 적록색약 (0) | 2017.07.14 |
---|---|
BOJ[백준] - 2589 - 보물섬 (0) | 2017.07.14 |
BOJ[백준] - 1753 - 최단경로 (0) | 2017.07.14 |
BOJ[백준] - 8984 - 막대기 (0) | 2017.07.13 |
BOJ[백준] - 1316 - 그룹 단어 체커 (0) | 2017.07.13 |