Advertisement
gelita

breadth first search

Feb 25th, 2020
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const fs = require('fs');
  4.  
  5. process.stdin.resume();
  6. process.stdin.setEncoding('utf-8');
  7.  
  8. let inputString = '';
  9. let currentLine = 0;
  10.  
  11. process.stdin.on('data', function(inputStdin) {
  12.     inputString += inputStdin;
  13. });
  14.  
  15. process.stdin.on('end', function() {
  16.     inputString = inputString.split('\n');
  17.  
  18.     main();
  19. });
  20.  
  21. function readLine() {
  22.     return inputString[currentLine++];
  23. }
  24.  
  25.  
  26.  
  27. /*
  28.  * Complete the 'bfs' function below.
  29.  *
  30.  * The function is expected to return a STRING.
  31.  * The function accepts following parameters:
  32.  *  1. Vertex origin
  33.  */
  34.  
  35. /*
  36.  * For your reference:
  37.  *
  38.  * Vertex {
  39.  *   char id;
  40.  *   edges[Vertex];
  41.  * }
  42.  *
  43.  */
  44. function bfs(origin) {
  45.   // Write your code here
  46.   if (!origin) return ""
  47.   let queue = []
  48.   queue.push(origin)
  49.   let output = []
  50.  
  51.   while (queue.length) {
  52.     // process queue
  53.     // add nodes to queue if not seen
  54.     let current = queue.shift()
  55.     if(output.includes(current.id)) continue
  56.     output.push(current.id)
  57.     let otherNodes = current.edges
  58.    
  59.     otherNodes.forEach(node => {
  60.         queue.push(node)
  61.     })
  62.  
  63.   }
  64.   return output.join("")
  65. }
  66.  
  67.  
  68. function main() {
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement