Guest User

Untitled

a guest
Mar 6th, 2020
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let bfs = (graph, root) => {
  2.   let nodesLen = {};
  3.  
  4.   for(let i = 0; i < graph.length; i++){
  5.     nodesLen[i] = Infinity; // Idicates that a node is not reachable from the start node
  6.   }
  7.   nodesLen[root] = 0; // The distance of the root node from the root node is set to 0
  8.  
  9.   let queue = [root] // Keep track of nodes we visit
  10.   let current; // Keep track of the current node we are traversing
  11.  
  12.   // This loop will keep traversing nodes in the queue until we have no other node to traverse
  13.   while(queue.length != 0){
  14.     current  = queue.shift() // Removes the first element in the array
  15.  
  16.     let curConnected = graph[current] // We get all the nodes connected to the current node
  17.     let neighborIdx = []
  18.     let idx = curConnected.indexOf(1) // Gets the index of the first node connected to the current node because the number one in our array shows that the node is connected to anothe node on that index
  19.  
  20.     // If there is no node at the index of one, the index variable will be set to -1.
  21.     while(idx != -1){
  22.       neighborIdx.push(idx) // So while index does not equals to -1, push our index onto our list of neighbors.
  23.       idx = curConnected.indexOf(1, idx + 1) // This line searches for the next connected node.
  24.     }
  25.  
  26.     // Now that we know all the nodes connected to the current node, we loop through this connected nodes, and get the distance
  27.     for ( let j = 0; j < neighborIdx.length; j++){
  28.       if (nodesLen[neighborIdx[j]] == Infinity){ // This line we haven't set the distance from the nodesLen[neighborIdx[j]] yet so we will set now.
  29.         nodesLen[neighborIdx[j]] = nodesLen[current] + 1
  30.         queue.push(neighborIdx[j]) // We push the neighbor to the queue so the next time we go through the while loop, we will check the neighbors of that node too.
  31.       }
  32.     }
  33.   }
  34.  
  35.   return nodesLen
  36. }
  37.  
  38. let exBFSGraph = [
  39.   [0,1,1,1,0],
  40.   [0,0,1,0,0],
  41.   [1,1,0,0,0],
  42.   [0,0,0,1,0],
  43.   [0,1,0,0,0]
  44. ]
  45.  
  46. bfs(exBFSGraph, 1)
Advertisement
Add Comment
Please, Sign In to add comment