Advertisement
gelita

find all paths search

Feb 25th, 2020
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function bfs(origin) {
  2.   // Write your code here
  3.   if (!origin) return ""
  4.   let queue = []
  5.   queue.push(origin)
  6.   let output = []
  7.  
  8.   while (queue.length) {
  9.     // process queue
  10.     // add nodes to queue if not seen
  11.     let current = queue.shift()
  12.     if(output.includes(current.id)) continue
  13.     output.push(current.id)
  14.     let otherNodes = current.edges
  15.    
  16.     otherNodes.forEach(node => {
  17.         queue.push(node)
  18.     })
  19.  
  20.   }
  21.   return output.join("")
  22. }
  23.  
  24. function find_all_paths(origin, destination) {
  25.   if(!origin) return []
  26.   // Write your code here
  27.   let output = []
  28.  
  29.   const helper = (currentNode, currentPath) => {
  30.     if(currentPath.includes(currentNode.id)) return
  31.    
  32.     if(currentNode.id === destination){
  33.       currentPath.push(currentNode.id)
  34.       output.push(currentPath.join(""))
  35.       return
  36.     }
  37.    
  38.     currentPath.push(currentNode.id)
  39.    
  40.     let otherNodes = currentNode.edges
  41.     otherNodes.forEach(node => {
  42.       helper(node, currentPath)
  43.     })
  44.    
  45.    
  46.   }
  47.  
  48.   helper(origin, [])
  49.  
  50.   return output
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement