-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (69 loc) · 1.56 KB
/
index.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
class Node {
constructor (value, relationships) {
this.value = value
this.relationships = relationships || new Set()
}
drawEdge (node) {
this.relationships.add(node.value)
node.relationships.add(this.value)
}
}
class Graph {
constructor (nodes) {
this.nodes = nodes || {}
}
add (value) {
const node = new Node(value)
this.nodes[node.value] = node
}
bfs (rootValue, value) {
const visited = new Set()
const q = []
const node = this.nodes[rootValue]
visited.add(node.value)
q.unshift(node)
while (q.length !== 0) {
let current = q.pop()
if (current.value === value) return current
current.relationships.forEach((v) => {
const n = this.nodes[v]
if (!visited.has(v)) {
visited.add(v)
n.parent = current
q.unshift(n)
}
})
}
}
dfs (rootValue, visited) {
visited = visited || new Set()
const node = this.nodes[rootValue]
visited.add(node.value)
node.relationships.forEach(n => {
if (!visited.has(n)) {
return this.dfs(n, visited)
}
})
return visited
}
shortestPath (rootValue, value) {
let result = this.bfs(rootValue, value)
const path = []
while (result.parent !== undefined) {
path.unshift(result.value)
result = result.parent
}
path.unshift(result.value)
return path
}
drawEdge (n, n2) {
const node = this.nodes[n]
const node2 = this.nodes[n2]
node.drawEdge(node2)
node2.drawEdge(node)
}
}
module.exports = {
Node,
Graph
}