class GraphEdgeSet:
"""
Assume: All vertices have __hash__ implemented
and __eq__ implemented
Let |V| be the number of vertices
and |E| be the number of edges
"""
def __init__(self):
self.V = set([])
self.E = set([])
def add_vertex(self, v):
self.V.add(v)
def add_edge(self, u, v):
self.E.add((u, v))
# NOTE: If (u, v) is in edges, we assume
# that (v, u) is also in edges
def get_neighbors(self, v):
## Loop through every edge and see if
## v is in that edge
## O(|E|)
neighbs = set([])
for (a, b) in self.E:
if a == v:
neighbs.add(b)
elif b == v:
neighbs.add(a)
return neighbs
graph = GraphEdgeSet()
for v in range(5):
graph.add_vertex(v)
graph.add_edge(0, 1)
graph.add_edge(1, 2)
graph.add_edge(1, 4)
graph.add_edge(4, 3)
graph.add_edge(1, 3)
for v in range(5):
print(v, graph.get_neighbors(v))
0 {1} 1 {0, 2, 3, 4} 2 {1} 3 {1, 4} 4 {1, 3}