-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.ts
105 lines (82 loc) · 2.23 KB
/
graph.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
export class Graph<T> {
private verticies: Set<T>;
private edges: Map<T, Set<T>>;
constructor() {
this.verticies = new Set();
this.edges = new Map();
}
private addVertex(vertex: T) {
if (this.verticies.has(vertex)) {
return;
}
this.verticies.add(vertex);
this.edges.set(vertex, new Set());
}
addEdge(vertexFrom: T, vertexTo: T) {
this.addVertex(vertexFrom);
this.addVertex(vertexTo);
const children = this.edges.get(vertexFrom);
children?.add(vertexTo);
}
addEdges(parent: T, children: T[]) {
this.addVertex(parent);
const allChildren = this.edges.get(parent);
children.forEach((child) => {
this.addVertex(child);
allChildren?.add(child);
});
}
print() {
this.visitEdges((vertex, children) => {
if (children.length === 0) return;
console.log(`${vertex}`, children);
});
}
dfs(vertex: T, visit: (vertex: T) => boolean | undefined) {
if (!this.verticies.has(vertex)) return;
const stack = [vertex];
const visited = new Set<T>();
while (stack.length !== 0) {
const currVertex = stack.pop();
if (!currVertex || visited.has(currVertex)) continue;
const skipChildren = visit(currVertex);
visited.add(currVertex);
if (skipChildren) {
continue;
}
const children = this.edges.get(currVertex)!;
stack.push(...Array.from(children));
}
}
/**
* Visits all edges in an unspecified order
*/
visitEdges = (fn: (vertex: T, children: T[]) => void) => {
this.verticies.forEach((vertex) => {
const children = this.edges.get(vertex);
fn(vertex, Array.from(children ?? []));
});
};
/**
* Visits all verticies in an unspecified order
*/
visitVerticies(fn: (vertex: T) => void) {
this.verticies.forEach(fn);
}
/**
* Visits each edge in an unspecified order
*/
visitEachEdge = (fn: (source: T, target: T) => void) => {
this.verticies.forEach((vertex) => {
const children = this.edges.get(vertex);
children?.forEach((target) => fn(vertex, target));
});
};
findChildren(vertex: T) {
const children = this.edges.get(vertex);
if (!children) {
return [];
}
return Array.from(children);
}
}