Skip to content

Instantly share code, notes, and snippets.

@seanreed1111
Last active December 31, 2015 14:18
Show Gist options
  • Save seanreed1111/7998985 to your computer and use it in GitHub Desktop.
Save seanreed1111/7998985 to your computer and use it in GitHub Desktop.
Breadth First Search
require '../lib/Queue'
frontier = Queue.new
# set up the adjacency list that defines the graph
neighbors = {}
neighbors = {:a => [:b,:f], :b => [:c,:d], :c => [:e], :d =>[:e], :e =>[:c,:d],
:f => [:a,:g,:h,:i], :g => [:f], :h => [:f], :i => [:f] }
parent = {}
visited = []
# :a is the source node for BFS search. Put :a into the frontier queue
parent[:a] = nil
frontier.enqueue(:a)
while !frontier.empty? do
frontier.each do |node|
neighbors[node].each do |neighbor|
if frontier.include?(neighbor) || visited.include?(neighbor)
next
else
frontier.enqueue(neighbor)
parent[neighbor] = node
end
end
end
visited << frontier.dequeue
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment