-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathgraph.search.js
72 lines (60 loc) · 1.71 KB
/
graph.search.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
(function (exports) {
const {stack} = require('../04-chapter-Stack/')
const {queue} = require('../05-chapter-Queue/')
let graph
let keys
const displayVertex = (node) => console.log(node)
const getUnvistedVertex = (vertex) => {
for (let node in graph[vertex].edges) {
if (graph[node].visited === false) {
return node
}
}
return false
}
const resetSearch = () => {
for (let node in graph) {
graph[node].visited = false
}
}
function dfs () {
graph = this.getGraph()
keys = Object.keys(graph)
let graphStack = stack()
graph[keys[0]].visited = true
displayVertex(keys[0])
graphStack.push(keys[0])
while (!graphStack.isEmpty()) {
let unvistedVertex = getUnvistedVertex(graphStack.peek())
if (unvistedVertex === false) {
graphStack.pop()
} else {
graph[unvistedVertex].visited = true
displayVertex(unvistedVertex)
graphStack.push(unvistedVertex)
}
}
resetSearch()
}
function bfs () {
graph = this.getGraph()
keys = Object.keys(graph)
let unvistedVertex
let graphQueue = queue()
graph[keys[0]].visited = true
displayVertex(keys[0])
graphQueue.enqueue(keys[0])
while (!graphQueue.isEmpty()) {
let tempVertex = graphQueue.dequeue()
unvistedVertex = getUnvistedVertex(tempVertex)
while (unvistedVertex !== false) {
graph[unvistedVertex].visited = true
displayVertex(unvistedVertex)
graphQueue.enqueue(unvistedVertex)
unvistedVertex = getUnvistedVertex(tempVertex)
}
}
resetSearch()
}
Object.assign(exports, {dfs, bfs})
}((typeof module.exports !== undefined) ? module.exports : window))