-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdfsAirportRoutes.js
More file actions
51 lines (43 loc) · 1.25 KB
/
Copy pathdfsAirportRoutes.js
File metadata and controls
51 lines (43 loc) · 1.25 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
const airports = 'ATL DXB DFW HND LHR DEN IST ORD DEL PVG LAX CAN CDG AMS SIN'.split(' ');
const routes = [
['ATL', 'LAX'],
['ATL', 'DFW'],
['DXB', 'ATL'],
['LAX', 'IST'],
['DEN', 'ORD'],
['DEN', 'PVG'],
['PVG', 'AMS'],
['DEL', 'AMS'],
['AMS', 'DXB'],
['AMS', 'LHR'],
['AMS', 'ATL'],
];
const adjacencyList = new Map();
function addNode(airport) {
adjacencyList.set(airport, []);
}
function addEdge(origin, destination) {
adjacencyList.get(origin).push(destination);
adjacencyList.get(destination).push(origin);
}
airports.forEach(addNode);
routes.forEach(route => addEdge(...route));
console.log(adjacencyList);
function findRoute(source, destination, visited = new Set(), foundRoute = []) {
visited.add(source);
foundRoute.push(source);
const destinations = adjacencyList.get(source);
for (const dest of destinations) {
if (dest === destination) {
foundRoute.push(destination);
return foundRoute;
}
// dfs recur
if (!visited.has(dest) && findRoute(dest, destination, visited, foundRoute)) return foundRoute;
}
foundRoute.pop();
return false;
}
// AMS -> LAX
const foundRoute = findRoute('AMS', 'LAX');
console.log(foundRoute ? `Find route: ${foundRoute.join(' -> ')}` : 'Route from AMS not found');