O'Reilly logo

Hands-On Data Structures and Algorithms with JavaScript by Kashyap Mukkamala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing the shortest path generation

Let's now create our customized BFS algorithm to parse the graph and generate the shortest possible path for our user to get referred to company A:

var _ = require('lodash');class Graph {   constructor(users) {      // initialize edges      this.edges = {};      // save users for later access      this.users = users;      // add users and edges of each      _.forEach(users, (user) => {         this.edges[user.id] = user.friends;      });   }   shortestPath(sourceUser, targetCompany) {      // final shortestPath      var shortestPath;      // for iterating along the breadth      var tail = 0;      // queue of users being visited      var queue = [ sourceUser ];      // mark visited users      var visitedNodes = [];      // previous path to backtrack steps when shortestPath is found      var prevPath ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required