forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
breadthFirstSearch.js
75 lines (62 loc) · 2.17 KB
/
breadthFirstSearch.js
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
import Queue from '../../../data-structures/queue/Queue';
/**
* @typedef {Object} Callbacks
*
* @property {function(vertices: Object): boolean} [allowTraversal] -
* Determines whether DFS should traverse from the vertex to its neighbor
* (along the edge). By default prohibits visiting the same vertex again.
*
* @property {function(vertices: Object)} [enterVertex] - Called when BFS enters the vertex.
*
* @property {function(vertices: Object)} [leaveVertex] - Called when BFS leaves the vertex.
*/
/**
* @param {Callbacks} [callbacks]
* @returns {Callbacks}
*/
function initCallbacks(callbacks = {}) {
const initiatedCallback = callbacks;
const stubCallback = () => {};
const allowTraversalCallback = (
() => {
const seen = {};
return ({ nextVertex }) => {
if (!seen[nextVertex.getKey()]) {
seen[nextVertex.getKey()] = true;
return true;
}
return false;
};
}
)();
initiatedCallback.allowTraversal = callbacks.allowTraversal || allowTraversalCallback;
initiatedCallback.enterVertex = callbacks.enterVertex || stubCallback;
initiatedCallback.leaveVertex = callbacks.leaveVertex || stubCallback;
return initiatedCallback;
}
/**
* @param {Graph} graph
* @param {GraphVertex} startVertex
* @param {Callbacks} [originalCallbacks]
*/
export default function breadthFirstSearch(graph, startVertex, originalCallbacks) {
const callbacks = initCallbacks(originalCallbacks);
const vertexQueue = new Queue();
// Do initial queue setup.
vertexQueue.enqueue(startVertex);
let previousVertex = null;
// Traverse all vertices from the queue.
while (!vertexQueue.isEmpty()) {
const currentVertex = vertexQueue.dequeue();
callbacks.enterVertex({ currentVertex, previousVertex });
// Add all neighbors to the queue for future traversals.
graph.getNeighbors(currentVertex).forEach((nextVertex) => {
if (callbacks.allowTraversal({ previousVertex, currentVertex, nextVertex })) {
vertexQueue.enqueue(nextVertex);
}
});
callbacks.leaveVertex({ currentVertex, previousVertex });
// Memorize current vertex before next loop.
previousVertex = currentVertex;
}
}