Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Created March 20, 2017 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegocasmo/d99fe084b24f45632956d35619e18dc9 to your computer and use it in GitHub Desktop.
Save diegocasmo/d99fe084b24f45632956d35619e18dc9 to your computer and use it in GitHub Desktop.
An implementation of the depth first search algorithm for undirected graphs.
class DFS
def initialize(graph={})
@graph = graph
@visited = {}
end
# This implementation of depth-first search visits
# only the portion of the graph reachable from the
# starting vertex
# Input: A vertex element of the graph
# Output: All reachable vertices from vertex
def dfs(vertex)
raise RuntimeError if @graph[vertex].nil?
@visited = {}
explore(@graph[vertex], vertex)
return @visited.keys - [vertex]
end
private
# Find all reachable vertices from a particular vertex
def explore(graph_of_vertex, current_vertex)
@visited[current_vertex] = true
graph_of_vertex.each do |vertex|
if not @visited[vertex]
explore(@graph[vertex], vertex)
end
end
end
end
@diegocasmo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment