-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreadth-first-search.mjs
70 lines (59 loc) · 1.23 KB
/
breadth-first-search.mjs
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
/**
* Search all possible routes from PHX and BKK
* RunTime complexity O(V+E) V= Node, E = edges
* Space complexity O(n) = linear
* It takes 8 steps to find the destination
* @param start node
*/
import { createGraph } from './implement-graph.mjs';
function bfs(graph, start, toFind) {
const queue = [];
queue.push(start);
const visited = new Set();
while (queue.length) {
var origin = queue.shift();
const destinations = graph.nodes.get(origin);
if (!destinations) continue;
for (const destination of destinations) {
if (toFind === destination) {
console.log('!! We found !!', toFind, 'in', visited.size, ' steps');
}
if (!visited.has(destination)) {
queue.push(destination);
visited.add(destination);
console.log(`Destination: ${destination}`);
}
}
}
}
const graph = createGraph();
bfs(graph, 'PHX', 'BKK');
bfs(graph, 'LIM', 'BKK');
/**
* PHX => [ ABC, XYZ ]
* ABC => [ BBB, CCC ]
*
* CCC => [ BKK, DDD ]
*
* s =[ ]
* o = phx
* a =[abc,xyz]
*
* s =[ xyz , bbb,ccc]
* o = abc
* a= [bbb,ccc]
*
* s =[ bbb,ccc]
* o = xyz
* a= null
*
*
* s =[ccc]
* o = bbb
* a= null
*
* s =[ccc]
* o = ccc
* a= [bkk, ddd]
* we found bkk
*/