Write a program to convert the given graph from matrix representation to linked list representation
Question
Write a program to convert the given graph from matrix representation to linked list representation
Solution
Sure, here is a Python program that converts a graph from matrix representation to adjacency list representation:
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def printGraph(self):
for v in range(self.V):
print("Adjacency list of vertex {}\n head".format(v), end="")
for neighbour in self.graph[v]:
print(" -> {}".format(neighbour), end="")
print(" \n")
def convert(matrix):
vertices = len(matrix)
g = Graph(vertices)
for i in range(vertices):
for j in range(vertices):
if matrix[i][j] == 1:
g.addEdge(i, j)
g.printGraph()
# Driver code
matrix = [[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0]]
convert(matrix)
This program first defines a Graph class with methods to add edges and print the graph. The convert function takes a matrix as input, creates a Graph object with the number of vertices equal to the length of the matrix, and then iterates over the matrix. If a cell in the matrix contains a 1, it adds an edge between the corresponding vertices in the graph. Finally, it prints the graph.
Similar Questions
- Contrast adjacency matrix and adjacency list representations for a graph. explain it for 5 marks
Apply the concept of a directed graph (digraph) by creating a visual representation with a neat diagram.
Write C Program to Find the Sum of Each Row and Column of a 2x2 Matrix - 15 marksSample InputEnter the co-efficients of the matrix
______data structure is most suitable for implementing a stack Array Linked list Tree Graph
Write C Program to Find the Sum of Each Row and Column of a 2x2 Matrix - 15 marksSample InputEnter the co-efficients of the matrix23 4580 97
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.