-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
56 lines (51 loc) · 1.52 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
class Graph {
constructor(maxVertices) {
this.maxVertices = maxVertices;
this.adjacencyList = new Map();
}
addVertex(vertex) {
if (this.adjacencyList.size >= this.maxVertices)
throw new Error("Exceeded number of vertices");
this.adjacencyList.set(vertex, []);
}
// assuming the graph is a undirected graph
addEdge(vertexA, vertexB) {
let neighboursOfA = this.adjacencyList.get(vertexA);
let neighboursOfB = this.adjacencyList.get(vertexB);
if (
neighboursOfA.indexOf(vertexB) !== -1 ||
neighboursOfB.indexOf(vertexA) !== -1
)
throw new Error("Duplicated edges");
neighboursOfA.push(vertexB);
neighboursOfB.push(vertexA);
}
displayGraph() {
const vertices = this.adjacencyList.keys();
for (const vertex of vertices) {
const edges = this.adjacencyList.get(vertex);
let neighbours = "";
for (const edge of edges) {
neighbours += edge + " ";
}
console.log(`${vertex} --> ${neighbours}`);
}
}
}
/**
* Creates and returns a graph using adjacencyList
* @param {any[]} adjacencyList
*/
const createGraph = function (adjacencyList) {
let vertices = [...new Set(adjacencyList.flat())];
const graph = new Graph(vertices.length);
for (const vertex of vertices) {
graph.addVertex(vertex);
}
for (const [vertexA, vertexB] of adjacencyList) {
graph.addEdge(vertexA, vertexB);
}
graph.displayGraph();
return graph;
};
module.exports = { createGraph };