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:
# Define the function to convert matrix to adjacency list
def convert_matrix_to_adj_list(matrix):
adj_list = {}
# Iterate over the matrix
for i in range(len(matrix)):
adj_list[i] = []
for j in range(len(matrix[i])):
# If there is an edge
if matrix[i][j] != 0:
adj_list[i].append(j)
return adj_list
# Define the graph in matrix representation
graph_matrix = [
[0, 1, 0, 1],
[1, 0, 1, 1],
[0, 1, 0, 1],
[1, 1, 1, 0]
]
# Convert the matrix to adjacency list
graph_adj_list = convert_matrix_to_adj_list(graph_matrix)
# Print the adjacency list
print(graph_adj_list)
In this program, we first define a function convert_matrix_to_adj_list that takes a matrix as input and returns an adjacency list. This function iterates over the matrix and for each non-zero entry in the matrix, it adds an edge in the adjacency list.
Then we define a graph in matrix representation and convert it to adjacency list using the function we defined. Finally, we print the adjacency list.
Similar Questions
Conversion of Graph from Matrix Representation to Linked List representationWrite a program to convert the given graph from matrix representation to linked list representationSample Input5 50 1 0 0 10 0 1 1 10 0 0 1 00 0 0 0 10 0 0 0 0output0 : -> 1 ->4 ->1 : -> 2 ->3 ->4 ->2 : -> 3 ->3 : -> 4 ->4 : ->
What is the simplest way of implementing a graph in C or C++? Ops: A. None of these B. Both Adjacency matrix and Associative lists C. Associative lists D. Adjacency matrix
Graph Representation - Linked ListWrite full code to represent the graph using linked list for the given input Note : Create undirected graphFor Example:input:5 70 10 41 21 31 42 33 4output:0 : -> 1 ->4 ->1 : -> 2 ->3 ->4 ->2 : -> 3 ->3 : -> 4 ->4 : ->Here vertex 0 is connected to vertex 1 and 41 is connected to 2,3,42 is connected to 33 is connected to 4
Write a python program that defines a matrix and prints
Which of the following ways can be used to represent a graph?Group of answer choicesAdjacency List, Adjacency Matrix as well as Incidence MatrixAdjacency List and Adjacency MatrixIncidence MatrixNo way to represent
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.