-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.rb
executable file
·78 lines (65 loc) · 1.24 KB
/
graph.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def to_nodes(hash)
roots = hash.keys
nodes = []
for root in roots
child_hash = hash[root]
children = to_nodes(child_hash)
nodes << Node.new(root, children)
end
nodes
end
class Node
attr_accessor :name, :children
def initialize(name, children = [])
@children = children
@name = name
end
def has_child?(some_node)
return @children.include?(some_node)
end
def to_s
@name
end
def inspect
to_s
end
end
class Graph
def initialize(root)
@root = root
end
def inspect
@root.inspect
end
def to_s
@root.to_s
end
def traverse(type, &block)
if type == :depth_first
traverse_depth_first(@root, block)
elsif type == :breadth_first
traverse_breadth_first(@root, block)
else
raise "unknown type #{type}"
end
end
private
def traverse_depth_first(node, block)
unless node.nil?
block.call(node)
for child in node.children
traverse_depth_first child, block
end
end
end
def traverse_breadth_first(node, block)
queue = [node]
while not queue.empty?
parent = queue.shift
block.call(parent)
for child in cursor.children
queue << child
end
end
end
end