Created
December 17, 2013 02:36
-
-
Save seanreed1111/7999053 to your computer and use it in GitHub Desktop.
Depth_First_Search
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
#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