-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathbreadthFirstSearch.js
More file actions
74 lines (61 loc) · 2.44 KB
/
Copy pathbreadthFirstSearch.js
File metadata and controls
74 lines (61 loc) · 2.44 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
import Queue from '../../../data-structures/queue/Queue';
/**
* @typedef {Object} Callbacks
*
* @property {function(vertices: Object): boolean} [allowTraversal] -
* Xác định xem có nên duyệt BFS từ đỉnh đến đỉnh kề của nó hay không (dọc theo cạnh).
* Theo mặc đỉnh, mỗi đỉnh chỉ được truy cập đúng một lần.
* @property {function(vertices: Object)} [enterVertex] - Được gọi khi BFS đi đến đỉnh.
*
* @property {function(vertices: Object)} [leaveVertex] - Được gọi khi BFS rời khỏi đỉnh.
*/
/**
* @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();
// Khởi tạo hàng đợi.
vertexQueue.enqueue(startVertex);
let previousVertex = null;
// Duyệt tất cả các đỉnh từ hành đợi.
while (!vertexQueue.isEmpty()) {
const currentVertex = vertexQueue.dequeue();
callbacks.enterVertex({ currentVertex, previousVertex });
// Thêm tất cả đỉnh kề vào hàng đợi cho việc duyệt trong tương lai.
graph.getNeighbors(currentVertex).forEach((nextVertex) => {
if (callbacks.allowTraversal({ previousVertex, currentVertex, nextVertex })) {
vertexQueue.enqueue(nextVertex);
}
});
callbacks.leaveVertex({ currentVertex, previousVertex });
// Lưu đỉnh hiện tại trước khi lặp lại.
previousVertex = currentVertex;
}
}