-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWeightedGraph.ts
235 lines (211 loc) · 5.63 KB
/
WeightedGraph.ts
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class PriorityQueue {
values;
constructor() {
this.values = [];
}
enqueue(val, protity) {
this.values.push({ val, protity });
this.bubbleUp();
}
bubbleUp() {
var idx = this.values.length - 1;
var element = this.values[idx];
while (idx > 0) {
var parentIdx = Math.floor((idx - 1) / 2);
var parent = this.values[parentIdx];
if (element.protity >= parent.protity) break;
this.values[parentIdx] = element;
this.values[idx] = parent;
idx = parentIdx;
}
}
isEmpty() {
return this.values.length === 0;
}
dequeue() {
if (this.values.length > 0) {
[this.values[0], this.values[this.values.length - 1]] = [
this.values[this.values.length - 1],
this.values[0],
];
}
var removed = this.values.pop();
this.bubbleDown();
return removed;
}
bubbleDown() {
var idx = 0;
var length = this.values.length;
var element = this.values[0];
while (true) {
var leftChildIdx = 2 * idx + 1;
var rightChildIdx = 2 * idx + 2;
var leftChild, rightChild;
var swap = null;
if (leftChildIdx < length) {
leftChild = this.values[leftChildIdx];
if (leftChild.protity < element.protity) {
swap = leftChildIdx;
}
}
if (
(rightChildIdx < length && swap === null) ||
(swap !== null && rightChild < leftChild)
) {
// inside the boundary
swap = rightChildIdx;
}
if (swap === null) break;
this.values[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
}
return this.values;
}
}
class Vertex {
adjacencyList: Edge[];
constructor(public label: string) {
this.label = label;
this.adjacencyList = [];
}
addEdge(to: string, weight: number) {
this.adjacencyList.push(new Edge(this.label, to, weight));
}
}
class Edge {
constructor(public from: string, public to: string, public weight: number) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
class Graph {
map = {};
addNode(val) {
const node = new Vertex(val);
if (!this.map[val]) this.map[val] = node;
}
addEdge(from: string, to: string, weight: number) {
if (!this.map[from] || !this.map[to] || from == to) return;
this.map[from].addEdge(to, weight);
this.map[to].addEdge(from, weight);
}
print() {
let set = new Set();
for (let node in this.map) {
let current = this.map[node];
for (let edge of current.adjacencyList) {
set.add(`${edge.from} -> ${edge.to} (W:${edge.weight})`);
}
}
return set;
}
// Dijkstra's Algorithm
shortestDistance(from, to) {
from = this.map[from];
if (!from || !to) return;
let distances = this._initDistance();
distances[from.label] = 0;
let previousNodes = {};
let visited = new Set();
let PQ = new PriorityQueue();
PQ.enqueue(from.label, 0);
while (!PQ.isEmpty()) {
let current = this.map[PQ.dequeue().val];
visited.add(current.label);
for (let n of current.adjacencyList) {
if (visited.has(n.to)) continue;
let newDistance = distances[current.label] + n.weight;
if (newDistance < distances[n.to]) {
distances[n.to] = newDistance;
previousNodes[n.to] = current.label;
PQ.enqueue(n.to, n.weight);
}
}
}
return distances[to];
}
_initDistance() {
let hashTable = {};
for (let n in this.map) {
hashTable[n] = Infinity;
}
return hashTable;
}
cycleDetection() {
let visited = new Set();
for (let node in this.map) {
const currentNode = this.map[node];
if (
!visited.has(currentNode.label) &&
this._cycleDetection(currentNode, visited, '')
) {
return true;
}
}
return false;
}
_cycleDetection(node: Vertex, visited, from: string) {
const adjacencyList = node.adjacencyList;
visited.add(node.label);
for (let n of adjacencyList) {
if (n.to == from) continue;
if (visited.has(n.to)) return true;
let nextNode = this.map[n.to];
if (this._cycleDetection(nextNode, visited, node.label)) {
return true;
}
}
return false;
}
//@ Prim's algorithm:
// Extend the tree by adding the smallest connected edge
minimumSpanningTree() {
const PQ = new PriorityQueue();
let visited = new Set();
let spanningTree = new Set();
let node = Object.keys(this.map)[0];
if (!node) return;
PQ.enqueue(this.map[node], 0);
while (!PQ.isEmpty()) {
let currentNode = PQ.dequeue().val;
visited.add(currentNode.label);
spanningTree.add(currentNode.label);
let adjacencyList = currentNode.adjacencyList;
for (let n of adjacencyList) {
if (visited.has(n.to)) continue;
PQ.enqueue(this.map[n.to], n.weight);
}
}
console.log(spanningTree);
return spanningTree;
}
}
const graph = new Graph();
// graph.addNode('A');
// graph.addNode('B');
// graph.addNode('C');
// graph.addNode('D');
// graph.addNode('E');
// graph.addEdge('A', 'B', 3);
// graph.addEdge('A', 'D', 2);
// graph.addEdge('A', 'C', 4);
// graph.addEdge('B', 'E', 1);
// graph.addEdge('B', 'D', 6);
// graph.addEdge('D', 'E', 5);
// graph.addEdge('D', 'C', 1);
// graph.print();
// console.log(graph.cycleDetection());
// console.log(graph.shortestDistance('A', 'E'));
// console.log(graph.map);
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addNode('D');
graph.addEdge('A', 'B', 3);
graph.addEdge('A', 'C', 1);
graph.addEdge('B', 'D', 4);
graph.addEdge('B', 'C', 2);
graph.addEdge('D', 'C', 5);
graph.minimumSpanningTree();