Skip to content

Instantly share code, notes, and snippets.

@seanreed1111
Created December 17, 2013 02:36
Show Gist options
  • Save seanreed1111/7999053 to your computer and use it in GitHub Desktop.
Save seanreed1111/7999053 to your computer and use it in GitHub Desktop.
Depth_First_Search
#defines DFS Object.
#currently only implements dfs_visit!, which only traverses the graph from one node
#to fully implement DFS, need to loop through ALL starting nodes
class DFS
attr_reader :adj_list, :parent
def initialize(adj_list={})
@adj_list = adj_list
@parent = {}
end
def dfs_run!(starting_node)
@parent[starting_node] = :none
dfs_visit!(starting_node, @adj_list[starting_node])
end
def dfs_visit!(node, adj_list_of_node)
adj_list_of_node.each do |vertex|
if !(parent.has_key?(vertex)) #if vertex is NOT in parent hash, it has not been explored
parent[vertex] = node
dfs_visit!(vertex,@adj_list[vertex])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment