Created
August 16, 2022 00:12
-
-
Save kevinlinxc/1deec5a6f491bbcedfeb92df9a917d21 to your computer and use it in GitHub Desktop.
Ruby depth-first-search function for blog post
This file contains 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
def dfs(start, target) | |
paths = [] | |
dfs_helper(start, target, [], paths) | |
paths | |
end | |
# note, no cyclic graphs allowed in dependencies, so no visited set needed | |
def dfs_helper(start, target, path, paths) | |
path << start | |
@graph[start].each do |node| | |
if node == target | |
path << target | |
paths << path.clone | |
else | |
dfs_helper(node, target, path.clone, paths) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment