-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathgraph.js
104 lines (84 loc) · 1.8 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
103
104
class Vertex {
constructor(key) {
this.key = key;
this.adjacent = [];
}
contains(key) {
for (let vertex of this.adjacent) {
if (vertex.key === key) {
return true;
}
}
return false;
}
}
class Graph {
constructor() {
this.vertices = [];
}
addVertex(key) {
if (this.contains(key)) {
console.log(`Vertex ${key} not added because it's an existent key`);
return;
}
this.vertices.push(new Vertex(key));
}
contains(key) {
for (let vertex of this.vertices) {
if (vertex.key === key) {
return true;
}
}
return false;
}
addEdge(from, to) {
let fromVertex = this.getVertex(from);
let toVertex = this.getVertex(to);
if (!fromVertex) {
console.log(`Vertex ${from} doesn't exist in the graph`);
return;
}
if (!toVertex) {
console.log(`Vertex ${to} doesn't exist in the graph`);
return;
}
if (fromVertex.contains(to)) {
console.log(`Existing edge: ${from} --> ${to}`);
return;
}
fromVertex.adjacent.push(toVertex);
}
getVertex(key) {
for (let vertex of this.vertices) {
if (vertex.key === key) {
return vertex;
}
}
}
print() {
for (let vertex of this.vertices) {
let adjacent = vertex.adjacent.reduce(
(verticesString, vertex) => `${verticesString} ${vertex.key}`,
''
);
console.log(`Vertice ${vertex.key}: ${adjacent}`);
}
}
}
const graph = new Graph();
graph.addVertex(0);
for (let i = 1; i <= 4; i++) {
graph.addVertex(i);
}
graph.addVertex(0);
graph.addVertex(0);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.addEdge(2, 4);
graph.addEdge(1, 2);
graph.addEdge(6, 2);
graph.addEdge(3, 2);
graph.addEdge(1, 1);
console.log();
graph.print();