-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
102 lines (78 loc) · 1.78 KB
/
graph.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
95
96
97
98
99
100
101
102
'use strict';
export default class Graph {
constructor (isDirected = false) {
this.isDirected = isDirected;
this.adjList = new Map();
}
addVertex (v) {
this.adjList.set(v, []);
}
addEdge (a, b) {
this.adjList.get(a).push(b);
if (!this.isDirected) {
this.adjList.get(b).push(a);
}
}
print () {
let output = '';
for (let vertex of this.adjList.keys()) {
let adjacencies = this.adjList.get(vertex);
let str = '';
adjacencies.forEach((adjVertex) => {
str += adjVertex + ' ';
});
output += `${vertex} => ${str}`;
}
console.log(output);
return output;
}
bfs (vertexA, vertexB) {
let q = [];
let visited = new Set();
q.push([vertexA]);
visited.add(vertexA);
while (q.length) {
let path = q.shift();
let v = path[path.length - 1];
if (v === vertexB) {
return path;
}
this.adjList.get(v).forEach((adjacent) => {
if (!visited.has(adjacent)) {
q.push(path.concat([adjacent]));
visited.add(adjacent);
}
});
}
return [];
}
dfs (vertexA, vertexB) {
let visited = new Set();
let adjList = this.adjList;
return dfsHelper(vertexA, []);
/**
* @param {*} v
* @param {Array} path
* @return {Array | boolean}
*/
function dfsHelper (v, path) {
path.push(v);
visited.add(v);
if (v === vertexB) {
return path;
}
for (let adjacent of adjList.get(v)) {
if (!visited.has(adjacent)) {
let result = dfsHelper(adjacent, path);
if (result.length) {
return result;
}
}
}
return [];
}
}
get vertices () {
return Array.from(this.adjList.keys());
}
}