Last active
August 14, 2016 20:34
-
-
Save Gabri3l/372adc4c07ac90383b777530b3b4ad06 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Description: | |
Implement a function solve_graph(start, end, arcs) that will return true if the end node can be reached from the start node, | |
using 0 or more arcs. It will return false if it is not possible. | |
The graph is defined by a list of arcs, where each arc is an object that has two properties, start and end, representing the | |
start and end nodes, respectively. Each arc is unidirectional, in other words it goes from a start node to an end node, and | |
not the other way around. Note that 0 or more arcs can leave a node, and 0 or more can arrive to it. | |
Note that the solve_graph() method doesn't take a list of nodes as input: for simplicity's sake, let's assume that all nodes | |
present in arcs are valid. However, the start or end node may not be in arcs. | |
An example | |
var arcs = [ | |
{ start : "a", end : "b" }, | |
{ start : "a", end : "a"} | |
]; | |
solve_graph("a", "b", arcs); // true | |
solve_graph("a", "c", arcs); // false | |
*/ | |
function solve_graph(start, end, arcs) { | |
let found = false; | |
let neighbors = []; | |
arcs.forEach((node) => {if(node.end === end) neighbors.push(node)}); | |
if (start === end) return arcs.some((n) => n.start === start ? true : false); | |
if (neighbors.length === 0) return false; | |
neighbors.forEach((node) => found = node.start === start ? true : solve_graph(start, node.start, arcs)); | |
return found; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment