-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_graphsWithAdjMatrixList.py
More file actions
67 lines (54 loc) · 1.89 KB
/
16_graphsWithAdjMatrixList.py
File metadata and controls
67 lines (54 loc) · 1.89 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
63
64
65
66
67
import numpy as np
class Vertex:
def __init__(self, val):
self.val = val
class Graph:
def __init__(self, vertices: list, n: int, isDir: bool):
self.vertices = vertices
self.matrix = np.zeros((n, n), dtype=int).tolist()
self.isDir = isDir
def checkVertexInGraph(self, vertex):
if vertex in self.vertices:
return True
return False
def connectEdge(self, vertex1, vertex2):
if not self.checkVertexInGraph(vertex1): return
if not self.checkVertexInGraph(vertex2): return
if not self.isDir:
self.matrix[self.vertices.index(vertex1)][self.vertices.index(vertex2)] = 1
self.matrix[self.vertices.index(vertex2)][self.vertices.index(vertex1)] = 1
print(f'edge created between {vertex1.val}, {vertex2.val}')
return
print('edge not created')
return
def disconnectEdge(self, vertex1, vertex2):
if not self.checkVertexInGraph(vertex1): return
if not self.checkVertexInGraph(vertex2): return
if not self.isDir:
self.matrix[self.vertices.index(vertex1)][self.vertices.index(vertex2)] = 0
self.matrix[self.vertices.index(vertex2)][self.vertices.index(vertex1)] = 0
print(f'edge removed between {vertex1.val}, {vertex2.val}')
return
print('edge not removed')
return
def getGraph(self):
if self.matrix:
for i in range(len(self.matrix)):
print(self.matrix[i])
return
print('graph not initialized')
return
a = Vertex('a')
b = Vertex('b')
c = Vertex('c')
d = Vertex('d')
graph1 = Graph([a, b, c, d], 4, False)
graph1.getGraph()
graph1.connectEdge(a, b)
graph1.connectEdge(b, c)
graph1.connectEdge(c, d)
graph1.connectEdge(d, a)
graph1.connectEdge(a, c)
graph1.getGraph()
graph1.disconnectEdge(a, c)
graph1.getGraph()