Skip to content

Instantly share code, notes, and snippets.

@seanreed1111
Last active September 21, 2016 01:31
Show Gist options
  • Select an option

  • Save seanreed1111/8029866 to your computer and use it in GitHub Desktop.

Select an option

Save seanreed1111/8029866 to your computer and use it in GitHub Desktop.
BFS Implementation. (Not defined as a Class)
require '../lib/Queue'
frontier = Queue.new
neighbors = {}
neighbors = {:a => [:b,:f],
:b => [:a,:c,:d],
:c => [:b,:e],
:d => [:b,: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