Last active
September 21, 2016 01:31
-
-
Save seanreed1111/8029866 to your computer and use it in GitHub Desktop.
BFS Implementation. (Not defined as a Class)
This file contains hidden or 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 | |
| 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