-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrapthWithAdjacencyMatrix.py
68 lines (52 loc) · 2.06 KB
/
GrapthWithAdjacencyMatrix.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
59
60
61
62
63
64
65
66
67
68
class Graph:
# Number of vertices
__n = 0
# Adjacency matrix
__g = [[0 for x in range(10)]
for y in range(10)]
# Constructor
def __init__(self, x):
self.__n = x
# Initializing each element of
# the adjacency matrix to zero
for i in range(0, self.__n):
for j in range(0, self.__n):
self.__g[i][j] = 0
# ------ A function to display adjacency matrix
def displayAdjacencyMatrix(self):
# Displaying the 2D matrix
for i in range(0, self.__n):
print()
for j in range(0, self.__n):
print("", self.__g[i][j], end = "")
# ------ A function to update adjacency matrix for edge insertion
def addEdge(self, x, y):
# Checks if the vertices
# exist in the graph
if (x < 0) or (x >= self.__n):
print("Vertex {} does not exist!".format(x))
if (y < 0) or (y >= self.__n):
print("Vertex {} does not exist!".format(y))
# Checks if it is a self edge
if(x == y):
print("Same Vertex!")
else:
# Adding edge between the vertices
self.__g[y][x] = 1
self.__g[x][y] = 1
# ------ A function to update adjacency matrix for edge removal
def removeEdge(self, x, y):
# Checks if the vertices
# exist in the graph
if (x < 0) or (x >= self.__n):
print("Vertex {} does not exist!".format(x))
if (y < 0) or (y >= self.__n):
print("Vertex {} does not exist!".format(y))
# Checks if it is a self edge
if(x == y):
print("Same Vertex!")
else:
# Remove edge from between
# the vertices
self.__g[y][x] = 0
self.__g[x][y] = 0