-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph_adjacency-matrix.py
58 lines (44 loc) · 1.58 KB
/
graph_adjacency-matrix.py
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
"""
Implementation of undirected Graph using Adjacency matrix, with weighted or unweighted edges
"""
class Vertex(object):
def __init__(self, name):
self.name = name
class Graph(object):
vertices = {}
edges = []
edge_indices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
for row in self.edges:
row.append(0)
self.edges.append([0] * (len(self.edges) + 1))
self.edge_indices[vertex.name] = len(self.edge_indices)
return True
else:
return False
def add_edge(self, u, v, weight=1):
if u in self.vertices and v in self.vertices:
self.edges[self.edge_indices[u]][self.edge_indices[v]] = weight
self.edges[self.edge_indices[v]][self.edge_indices[u]] = weight
return True
else:
return False
def print_graph(self):
for v, i in sorted(self.edge_indices.items()):
print(v + ' ', end='')
for j in range(len(self.edges)):
print(self.edges[i][j], end='')
print(' ')
if __name__ == "__main__":
g = Graph()
a = Vertex('A')
g.add_vertex(a)
g.add_vertex(Vertex('B'))
for i in range(ord('A'), ord('K')):
g.add_vertex(Vertex(chr(i)))
edges = ['AB', 'AE', 'BF', 'CG', 'DE', 'DH', 'EH', 'FG', 'FI', 'FJ', 'GJ', 'HI']
for edge in edges:
g.add_edge(edges[:1], edge[1:])
g.print_graph()