Last active
March 17, 2016 03:31
-
-
Save jmsevold/759bfc821145ab2d6162 to your computer and use it in GitHub Desktop.
Breadth First Search Implementation for Beginners
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
class Node | |
attr_reader :value, :children,:distance | |
attr_writer :distance | |
def initialize(value, children = []) | |
@value = value | |
@children = children | |
@distance = 0 | |
end | |
end | |
=begin | |
1 | |
/ \ | |
2 3 | |
/ \ | |
4 5 | |
Write the method :bfs so that it prints out the tree like this: | |
$ bfs(node1) | |
'1' | |
'2' | |
'3' | |
'4' | |
'5' | |
TIPS: | |
Ruby provides a Queue class, which has the methods :enq, :deq, and :empty? | |
=end | |
# print value and children if any | |
node5 = Node.new(5) | |
node4 = Node.new(4) | |
node3 = Node.new(3, [node4, node5]) | |
node2 = Node.new(2) | |
node1 = Node.new(1, [node2, node3]) | |
node1.distance = 0 | |
def bfs(node) | |
queue = Queue.new | |
queue.enq(node) | |
while !queue.empty? | |
current_node = queue.deq | |
p "Node #{current_node.value} has a distance of #{current_node.distance} from source: Node #{node.value}" | |
if current_node.children.any? | |
current_node.children.each do |child| | |
child.distance = current_node.distance + 1 | |
queue.enq(child) | |
end | |
end | |
end | |
end | |
bfs(node1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment