-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS_DFS.js
56 lines (51 loc) · 1.04 KB
/
BFS_DFS.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
/**
* @see https://www.bilibili.com/video/BV1Ks411579J
*/
const graph = {
"A": ["B", "C"],
"B": ["A", "C", "D"],
"C": ["A", "B", "D", "E"],
"D": ["B", "C", "E", "F"],
"E": ["C", "D"],
"F": ["D"],
}
function BFS(graph, s) {
const queue = []
queue.push(s)
const seen = []
seen.push(s)
while(queue.length != 0) {
vertex = queue.shift()
console.log(`${vertex}`)
const nodes = graph[vertex]
for (let i = 0; i < nodes.length; i++) {
if(!seen.includes(nodes[i])) {
const node = nodes[i]
queue.push(node)
seen.push(node)
}
}
}
}
console.log("BFS:")
BFS(graph, "A")
function DFS(graph, s) {
const stack = []
stack.push(s)
const seen = []
seen.push(s)
while(stack.length != 0) {
vertex = stack.pop()
console.log(`${vertex}`)
const nodes = graph[vertex]
for (let i = 0; i < nodes.length; i++) {
if(!seen.includes(nodes[i])) {
const node = nodes[i]
stack.push(node)
seen.push(node)
}
}
}
}
console.log("DFS:")
DFS(graph, "A")