Skip to content

Instantly share code, notes, and snippets.

@rahulkmr
Created February 10, 2012 17:58
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 rahulkmr/1791284 to your computer and use it in GitHub Desktop.
Save rahulkmr/1791284 to your computer and use it in GitHub Desktop.
def graph_search(graph, initial, queue)
queue.enqueue(initial)
seen = {}
while not queue.empty?
node = queue.dequeue
puts node
seen[node] = true
if graph[node]
graph[node].each {|child| queue.enqueue child unless seen[child] }
end
end
end
def dfs_search(graph, initial)
stack = Array.new
def stack.enqueue(el); push(el); end
def stack.dequeue; pop; end
graph_search(graph, initial, stack)
end
def bfs_search(graph, initial)
queue = Array.new
def queue.enqueue(el); push(el); end
def queue.dequeue; shift; end
graph_search(graph, initial, queue)
end
graph = {a: [:b, :c], b: [:d, :e], c: [:f, :g]}
dfs_search(graph, :a)
bfs_search(graph, :a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment