-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.js
78 lines (64 loc) · 1.71 KB
/
graph.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
76
77
78
/** reference : https://fireship.io/courses/javascript/interview-graphs/
* https://www.youtube.com/watch?v=cWNEl4HE2OE&ab_channel=Fireship
* time complexity : O(n)
*/
const airports = 'PHX BKK OKC JFK LAX MEX EZE HEL LOS LAP LIM'.split(' ');
const routes = [
['PHX', 'LAX'],
['PHX', 'JFK'],
['JFK', 'OKC'],
['JFK', 'HEL'],
['JFK', 'LOS'],
['MEX', 'LAX'],
['MEX', 'BKK'],
['MEX', 'LIM'],
['MEX', 'EZE'],
['LIM', 'BKK']
];
const adjacencyList = new Map();
const addNode = (airport) => {
adjacencyList.set(airport, []);
}
const addEdge = (origin, destination) => {
adjacencyList.get(origin).push(destination);
adjacencyList.get(destination).push(origin);
//console.log(adjacencyList);
}
airports.forEach(addNode);
routes.forEach(route => addEdge(...route));
/** BFS Breadth First Search */
const bfs = (start) => {
const visited = new Set();
const queue = [start];
while (queue.length > 0) {
const airport = queue.shift();
const destinations = adjacencyList.get(airport);
for (const destination of destinations) {
if (destination === 'BKK') {
console.log('found it!');
}
if (!visited.has(destination)) {
visited.add(destination);
queue.push(destination);
console.log(destination)
}
}
}
}
//bfs('PHX');
/** DFS Depth First Search */
const dfs = (start, visited = new Set()) => {
console.log(start);
visited.add(start);
const destinations = adjacencyList.get(start);
for (const destination of destinations) {
if (destination === 'BKK') {
console.log('DPS found BKK in steps');
return ;
}
if (!visited.has(destination)) {
dfs(destination, visited);
}
}
}
//dfs('PHX');