-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.ts
More file actions
57 lines (46 loc) · 1.52 KB
/
Graph.ts
File metadata and controls
57 lines (46 loc) · 1.52 KB
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
export class Graph<T> {
private _adjacencyList: Object | any = {};
public get adjacencyList(): Object | any {
return this._adjacencyList;
}
private set adjacencyList(v: Object | any) {
this._adjacencyList = v;
}
constructor() {
this.adjacencyList = {}
}
addVertex(vertex: T): boolean {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
return true;
}
return false;
}
addEdge(vertex1: T, vertex2: T): boolean {
if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
return true;
}
return false;
}
removeEdge(vertex1: T, vertex2: T): boolean {
if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) {
this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter((v: T) => v !== vertex2);
this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter((v: T) => v !== vertex1);
return true;
}
return false;
}
removeVertex(vertex: T): Graph<T> | undefined {
if (!this.adjacencyList[vertex]) {
return undefined;
}
while (this.adjacencyList[vertex].length) {
let temp = this.adjacencyList[vertex].pop();
this.removeEdge(vertex, temp);
}
delete this.adjacencyList[vertex];
return this;
}
}