Last active
May 15, 2022 10:52
-
-
Save jps/abe15de42c6a6e6539e2210be584f03b to your computer and use it in GitHub Desktop.
graphs depth first has path - https://structy.net/problems/has-path
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
| //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