-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.rb
More file actions
40 lines (30 loc) · 918 Bytes
/
graph.rb
File metadata and controls
40 lines (30 loc) · 918 Bytes
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
class Graph
attr_reader :nodes, :weights
def initialize(options = {})
# Nodes connections are stored like:
# { some_node => { another_node => weight, yet_another_node => weight}, another_node => ... }
@nodes = []
@weights = {}
end
def add_edge(node, other_node, weight)
if @weights.has_key?(node)
@weights[node][other_node] = weight
else
@weights[node] = { other_node => weight }
end
if @weights.has_key?(other_node)
@weights[other_node][node] = weight
else
@weights[other_node] = { node => weight }
end
@nodes << node unless @nodes.include?(node)
@nodes << other_node unless @nodes.include?(other_node)
end
def children_of(node)
@weights[node].keys
end
def shortest_path(source_node, destination_node)
dijkstra = DijkstraAlgorithm.new(self)
dijkstra.shortest_path(source_node, destination_node)
end
end