-
-
Notifications
You must be signed in to change notification settings - Fork 307
Expand file tree
/
Copy pathunweighted_graph.rb
More file actions
62 lines (53 loc) · 1.5 KB
/
unweighted_graph.rb
File metadata and controls
62 lines (53 loc) · 1.5 KB
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
require 'set'
##
# This class aims to represent unweighted graphs
# (i.e. graphs for which edges between nodes have no specific weight associated to them).
#
# Both directed (i.e. an edge between node U and node V does not imply an edge in the opposite direction)
# and undirected graphs are supported, depending on the constructor invocation.
class UnweightedGraph
attr_reader :nodes
attr_reader :directed
def initialize(nodes: [], neighbors: {}, directed: true)
@nodes = Set[]
@neighbors = {}
@directed = directed
for node in nodes
add_node(node)
end
neighbors.each do |node, neighbors|
for neighbor in neighbors
add_edge(node, neighbor)
end
end
end
def add_node(node)
if include?(node)
raise ArgumentError, "node #{node} already exists in this graph!"
end
@nodes.add(node)
@neighbors[node] = Set[]
end
def add_edge(start_node, end_node)
if has_neighbor?(start_node, end_node)
raise ArgumentError, "node #{start_node} already has an edge to #{end_node} in this graph!"
end
@neighbors[start_node].add(end_node)
@neighbors[end_node].add(start_node) unless directed
end
def neighbors(node)
unless include?(node)
raise ArgumentError, "node #{node} does not exist in this graph!"
end
@neighbors[node]
end
def empty?
nodes.empty?
end
def include?(node)
nodes.include?(node)
end
def has_neighbor?(start_node, end_node)
neighbors(start_node).include?(end_node)
end
end