-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathgraph.js
More file actions
113 lines (86 loc) · 2.37 KB
/
graph.js
File metadata and controls
113 lines (86 loc) · 2.37 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
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
class Graph {
#vertices = new Set();
#adjacentList = new Map();
get vertices() {
return Array.from(this.#vertices)
}
get adjacentList() {
const list = {};
this.#adjacentList.forEach((val, key) => {
list[key] = Array.from(val)
})
return list
}
addVertex(vertex = null) {
if(vertex !== null && vertex !== undefined) {
this.#vertices.add(vertex);
this.#adjacentList.set(vertex, new Set());
}
}
addEdge(vertex1 = null, vertex2 = null, directed = true) {
if(
vertex1 !== null && vertex1 !== undefined &&
vertex2 !== null && vertex2 !== undefined &&
vertex1 != vertex2
) {
if(!this.#adjacentList.has(vertex1)) {
this.addVertex(vertex1);
}
if(!this.#adjacentList.has(vertex2)) {
this.addVertex(vertex2);
}
this.#adjacentList.get(vertex1).add(vertex2);
if(directed) {
this.#adjacentList.get(vertex2).add(vertex1);
}
}
}
toString() {
let str = '';
this.#adjacentList.forEach((val, key) => {
str += `${key} -> ${Array.from(val).join(', ')};\n`;
});
return str;
}
}
const COLORS = Object.freeze({
GREEN: 'green',
YELLOW: 'yellow',
RED: 'red'
});
function breathFirstSearch(graph, fromVertex, callback) {
const {vertices, adjacentList} = graph;
if(vertices.length === 0) return;
const color = vertices.reduce((c, v) => ({...c, [v]: COLORS.GREEN}), {});
const queue = [];
queue.push(fromVertex);
while(queue.length) {
const v = queue.shift();
const nearVertex = adjacentList[v];
color[v] = COLORS.YELLOW;
nearVertex.forEach(w => {
if(color[w] === COLORS.GREEN) {
color[w] = COLORS.YELLOW;
queue.push(w);
}
});
color[v] = COLORS.RED;
callback && callback(v);
}
}
function depthFirstSearch(graph, fromVertex, callback) {
const {vertices, adjacentList} = graph;
if(vertices.length === 0) return;
const color = vertices.reduce((c, v) => ({...c, [v]: COLORS.GREEN}), {});
callback && callback(fromVertex);
color[fromVertex] = COLORS.YELLOW;
function visit(v) {
if(color[v] === COLORS.GREEN) {
callback && callback(v);
color[v] = COLORS.YELLOW;
adjacentList[v].forEach(visit);
}
color[v] = COLORS.RED;
}
adjacentList[fromVertex].forEach(visit);
}