Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const adjList = {
- 1: [2, 5],
- 2: [1, 3, 5],
- 3: [2, 4],
- 4: [3, 5],
- 5: [1, 2, 4],
- 6: []
- }
- function aShortestPath(start, end) {
- let queue = [];
- let array = [start];
- let visited = new Set();
- visited.add(start);
- queue.push(array);
- while(queue.length > 0){
- let currentPath = queue.shift();
- let currentNode = currentPath[currentPath.length - 1];
- if(currentNode === end){
- return currentPath;
- }
- let neighbors = adjList[currentNode];
- for(let neighbor of neighbors){
- if(!visited.has(neighbor)){
- let newPath = currentPath.concat(neighbor);
- visited.add(neighbor);
- queue.push(newPath);
- }
- }
- }
- return false;
- }
- console.log("First Test:");
- console.log(aShortestPath(1, 3)); // -> [ 1, 2, 3 ] (One possible solution)
- console.log("Second Test:");
- console.log(aShortestPath(4, 1)); // -> [ 4, 5, 1 ] (One possible solution)
- console.log("Third Test:");
- console.log(aShortestPath(6, 1)); // -> false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement