Skip to content

Instantly share code, notes, and snippets.

@kevinlinxc
Created August 16, 2022 00:12
Show Gist options
  • Save kevinlinxc/1deec5a6f491bbcedfeb92df9a917d21 to your computer and use it in GitHub Desktop.
Save kevinlinxc/1deec5a6f491bbcedfeb92df9a917d21 to your computer and use it in GitHub Desktop.
Ruby depth-first-search function for blog post
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