Last active
December 31, 2015 19:29
-
-
Save seanreed1111/8033558 to your computer and use it in GitHub Desktop.
DFS as a class
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
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 | |
private | |
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
a DFS object should be initialized with the adjacency list defining the graph to be traversed as a hash of the form
adj = { :a => [:b,:c], :b => [:a], :c => [:a]}.
The hash adj shows all nodes and symbols, with the key,value pairs as the node and an array of all nodes reachable in one step.
When dfs_run! message is sent to the object, the parent hash is computed and saved as an instance variable.