Last active
December 31, 2015 14:18
-
-
Save seanreed1111/7998985 to your computer and use it in GitHub Desktop.
Breadth First Search
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
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