DFS와 BFS
문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
출력
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
입출력 예제
//입력1
4 5 1
1 2
1 3
1 4
2 4
3 4
//출력1
1 2 4 3
1 2 3 4
//입력2
5 5 3
5 4
5 2
1 2
3 4
3 1
//출력2
3 1 2 5 4
3 1 4 2 5
//입력3
1000 1 1000
999 1000
//출력3
1000 999
1000 999
👍 #. 풀이확인 JS 👍
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
88
89
90
91
92
93
94
| let input = require('fs').readFileSync('/dev/stdin')
let data = input.toString().trim().split(/\n+/).map(i => i.toString().trim().split(/\s+/).map(n => +n))
const [ N, M, start ] = data[0]
const edgeList = data.slice(1)
const linkedList = new Map()
const visited = new Map()
const setVertex = (visited, item) => {
const [parent, child] = item
if (!visited.has(parent)) {
visited.set(parent, false)
}
if (!visited.has(child)) {
visited.set(child, false)
}
}
const setLinkedList = (linkedList, item) => {
const [parent, child] = item
if (!linkedList.has(parent)) {
linkedList.set(parent, [child])
} else {
linkedList.get(parent).push(child)
}
if (!linkedList.has(child)) {
linkedList.set(child, [parent])
} else {
linkedList.get(child).push(parent)
}
}
const init = () => {
// Add likedList, visited
if (!visited.size) {
for (let i = 0; i < M; i++) {
setVertex(visited, edgeList[i])
}
}
if (!linkedList.size) {
for (let i = 0; i < M; i++) {
setLinkedList(linkedList, edgeList[i])
}
}
}
// DFS
const result = []
const stack = []
const dfs = (start) => {
stack.push(start)
visited.set(start, true)
while (stack.length) {
const last = stack[stack.length - 1]
result.push(stack.pop())
if (linkedList.has(last) && linkedList.get(last).length) {
for (const item of linkedList.get(last).sort((a, b) => (a - b))) {
if (!visited.get(item)) {
dfs(item)
}
}
}
}
}
// BFS
const queue = []
const bfs = (start) => {
queue.push(start)
visited.set(start, true)
while (queue.length) {
const first = queue[0]
result.push(queue.shift())
if (linkedList.get(first) && linkedList.get(first).length) {
linkedList.get(first).sort((a, b) => a - b).forEach(item => {
if (!visited.get(item)) {
queue.push(item)
visited.set(item, true)
}
})
}
}
console.log(result.join(' '))
}
init()
dfs(start)
console.log(result.join(' '))
visited.clear()
result.length = 0
stack.length = 0
init()
bfs(start)
|