Skip to content

Instantly share code, notes, and snippets.

@jps
Last active May 15, 2022 10:52
Show Gist options
  • Select an option

  • Save jps/abe15de42c6a6e6539e2210be584f03b to your computer and use it in GitHub Desktop.

Select an option

Save jps/abe15de42c6a6e6539e2210be584f03b to your computer and use it in GitHub Desktop.
graphs depth first has path - https://structy.net/problems/has-path
//breadth first iterative
const hasPath = (graph, src, dst) => {
let queue = [src];
while(queue.length > 0)
{
let current = queue.shift()
if(current === dst)
{
return true;
}
for(let edge of graph[current])
{
queue.push(edge);
}
}
return false;
}
//recursive depth first
const hasPathDepthFirstRecursive = (graph, src, dst) => {
return graph[src].some(edge => edge === dst || hasPath(graph, edge, dst))
};
//iterative using stack
const hasPathStack = (graph, src, dst) => {
let stack = [];
stack.push(...graph[src])
while(stack.length > 0)
{
let currentNode = stack.pop();
if(currentNode === dst)
{
return true;
}
for(let edge of graph[currentNode])
{
stack.push(edge);
}
}
return false;
};
module.exports = {
hasPath
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment