class GraphAdjList:
def __init__(self, n):
self.n = n
self.adj = [[] for _ in range(n)]
def add_edge(self, u, v):
self.adj[u].append(v) # add v to u's list
self.adj[v].append(u) # add u to v's list (undirected)
def __str__(self):
result = []
for i in range(self.n):
neighbors = ' -> '.join(str(x) for x in self.adj[i]) + ' -> null'
result.append(f'{i}: {neighbors}')
return '\n'.join(result)
class GraphAdjMatrix:
def __init__(self, n):
self.n = n
self.matrix = [[0]*n for _ in range(n)]
def add_edge(self, u, v):
self.matrix[u][v] = 1 # mark edge u-v
self.matrix[v][u] = 1 # mark edge v-u (undirected)
def __str__(self):
header = ' ' + ' '.join(str(i) for i in range(self.n))
rows = []
for i in range(self.n):
row = ' '.join(str(x) for x in self.matrix[i])
rows.append(f'{i} [{row}]')
return header + '\n' + '\n'.join(rows)
# Driver code
n = 4
edges = [(0,1),(0,2),(1,3)]
# Create adjacency list graph
graph_list = GraphAdjList(n)
for u,v in edges:
graph_list.add_edge(u,v)
print('Adjacency List:')
print(graph_list)
# Create adjacency matrix graph
graph_matrix = GraphAdjMatrix(n)
for u,v in edges:
graph_matrix.add_edge(u,v)
print('\nAdjacency Matrix:')
print(graph_matrix)
# Add edge 2-3
graph_list.add_edge(2,3)
graph_matrix.add_edge(2,3)
print('\nAfter adding edge 2-3:')
print('Adjacency List:')
print(graph_list)
print('\nAdjacency Matrix:')
print(graph_matrix)self.adj[u].append(v) # add v to u's list
add neighbor v to node u's adjacency list
self.adj[v].append(u) # add u to v's list (undirected)
add neighbor u to node v's adjacency list for undirected graph
self.matrix[u][v] = 1 # mark edge u-v
mark presence of edge from u to v in matrix
self.matrix[v][u] = 1 # mark edge v-u (undirected)
mark presence of edge from v to u in matrix for undirected graph
Adjacency List:
0: 1 -> 2 -> null
1: 0 -> 3 -> null
2: 0 -> null
3: 1 -> null
Adjacency Matrix:
0 1 2 3
0 [0 1 1 0]
1 [1 0 0 1]
2 [1 0 0 0]
3 [0 1 0 0]
After adding edge 2-3:
Adjacency List:
0: 1 -> 2 -> null
1: 0 -> 3 -> null
2: 0 -> 3 -> null
3: 1 -> 2 -> null
Adjacency Matrix:
0 1 2 3
0 [0 1 1 0]
1 [1 0 0 1]
2 [1 0 0 1]
3 [0 1 1 0]