-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.ts
89 lines (82 loc) · 2.17 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
import { print } from "./util";
export class Graph<T> {
private vertices: number;
private edges: number;
private adj: any;
private dfs_marked: any;
private bfs_marked: any;
private path: any;
constructor(n: number) {
this.vertices = n;
this.edges = 0;
this.adj = {};
this.dfs_marked = {};
this.bfs_marked = {};
this.path = {};
}
public addEdge(v: T, w: T) {
if (this.adj[v] == undefined) {
this.adj[v] = new Array<T>();
}
if (this.adj[w] == undefined) {
this.adj[w] = new Array<T>();
}
this.adj[v].push(w);
this.adj[w].push(v);
this.edges++;
}
// depth first search
public dfs(v: T) {
this.dfs_marked[v] = true;
if (this.adj[v] != undefined) {
print("[DFS] Visited vertex: ", v);
}
let d = this.adj[v];
for (let w of d) {
if (!this.dfs_marked[w]) {
this.dfs(w);
}
}
}
// broad first search
public bfs(v: T) {
let queue = new Array<T>();
if (this.adj[v] != undefined) {
queue.push(v);
}
do {
let w = queue.shift();
print("[BFS] Visited vertex: ", w);
this.bfs_marked[w] = true;
let d = this.adj[w];
for (let v of d) {
if (!this.bfs_marked[v]) {
this.path[v] = w;
queue.push(v);
}
}
} while (queue.length > 0);
}
// find the shortest path
public findShortestPath(v: T):T[] {
let path = [];
if(!this.bfs_marked[v]) {
print("no edge to vertex or no vertex in the graph: ",v);
return undefined;
}
for(let e = v; e!=undefined; e=this.path[e]){
path.push(e);
}
return path;
}
public showGraph() {
for (let k in this.adj) {
let s = k + " -> ";
let d = this.adj[k];
for (let j = 0; j < d.length; j++) {
s += d[j] + ' ';
}
print(s);
}
}
}