forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdepth-first-search.ts
103 lines (92 loc) · 2.24 KB
/
depth-first-search.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
import Graph from '../../data-structures/graph';
enum Colors {
WHITE = 0,
GREY = 1,
BLACK = 2
}
const initializeColor = (vertices: (string | number)[]) => {
const color: any = {};
for (let i = 0; i < vertices.length; i++) {
color[vertices[i]] = Colors.WHITE;
}
return color;
};
const depthFirstSearchVisit = (
u: string | number,
color: any,
adjList: any,
callback: Function
) => {
color[u] = 'grey';
if (callback) {
callback(u);
}
// console.log('Discovered ' + u);
const neighbors = adjList.get(u);
for (let i = 0; i < neighbors.length; i++) {
const w = neighbors[i];
if (color[w] === Colors.WHITE) {
depthFirstSearchVisit(w, color, adjList, callback);
}
}
color[u] = Colors.BLACK;
// console.log('explored ' + u);
};
export const depthFirstSearch = (graph: Graph, callback: Function) => {
const vertices = graph.getVertices();
const adjList = graph.getAdjList();
const color = initializeColor(vertices);
for (let i = 0; i < vertices.length; i++) {
if (color[vertices[i]] === Colors.WHITE) {
depthFirstSearchVisit(vertices[i], color, adjList, callback);
}
}
};
const DFSVisit = (
u: string | number,
color: any,
d: any,
f: any,
p: any,
time: number,
adjList: any
) => {
// console.log('discovered ' + u);
color[u] = Colors.GREY;
d[u] = ++time;
const neighbors = adjList.get(u);
for (let i = 0; i < neighbors.length; i++) {
const w = neighbors[i];
if (color[w] === Colors.WHITE) {
p[w] = u;
DFSVisit(w, color, d, f, p, time, adjList);
}
}
color[u] = Colors.BLACK;
f[u] = ++time;
// console.log('explored ' + u);
};
export const DFS = (graph: Graph) => {
const vertices = graph.getVertices();
const adjList = graph.getAdjList();
const color = initializeColor(vertices);
const d: any = {};
const f: any = {};
const p: any = {};
const time = 0;
for (let i = 0; i < vertices.length; i++) {
f[vertices[i]] = 0;
d[vertices[i]] = 0;
p[vertices[i]] = null;
}
for (let i = 0; i < vertices.length; i++) {
if (color[vertices[i]] === Colors.WHITE) {
DFSVisit(vertices[i], color, d, f, p, time, adjList);
}
}
return {
discovery: d,
finished: f,
predecessors: p
};
};