The program goal is to traverse through various airports and output the shortest path between PHX and BKK using Breadth First Search algorithm. However, I am facing difficulty in printing the result.
The expected output (shortest path) is: PHX -> LAX -> MEX -> BKK
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'],
];
// The graph
const adjacencyList = new Map();
// Add node
function addNode(airport) {
adjacencyList.set(airport, []);
}
// Add edge, undirected
function addEdge(origin, destination) {
adjacencyList.get(origin).push(destination);
adjacencyList.get(destination).push(origin);
}
// Create the Graph
airports.forEach(addNode);
// loop through each route and spread the values into addEdge function
routes.forEach(route => addEdge(...route));
Adding nodes as the origin(station), and edges as the destination, the graph is undirected
function bfs(start) {
const visited = new Set();
visited.add(start); // adding the starting node into the visited list
const queue = [start];
while (queue.length > 0) {
const airport = queue.shift(); // mutates the queue
const destinations = adjacencyList.get(airport);
for (const destination of destinations) {
if (destination === 'BKK') {
console.log(`BFS found Bangkok!`)
//console.log(path);
}
if (!visited.has(destination)) {
visited.add(destination);
queue.push(destination);
}
}
}
}
bfs('PHX')
2
Answers
I was able to solve the issue following InSync suggestion in the comments
code in bfs(): oldpath is used to store the path taken for each node (parentNode) shortest path is used to store the result
the new function job is simple, add the parentNode to the shortesPath then find the parent of the parentNode if exists, the loop quits when the current parentNode is the Root
Instead of marking a node as visited, use that opportunity to mark that node with its parent node. You can use one Map to:
I would also avoid referencing global variables in functions, and instead pass all that is needed as arguments: