January 2018
Intermediate to advanced
332 pages
7h 36m
English
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 ...
Read now
Unlock full access