Posted on by Kalkicode
Code Graph

Python program for Construct adjacency list by using adjacency matrix. Here problem description and other solutions.

``````#    Python 3 program for
class Graph :
def __init__(self, matrix) :
#  Set number of nodes
self.vertices = len(matrix)
i = 0
#  Create memory of adgeList of each vertice
while (i < self.vertices) :
i += 1

i = 0
while (i < self.vertices) :
j = 0
while (j < self.vertices) :
if (matrix[i][j] == 1) :

j += 1

i += 1

if (u < 0 or u >= self.vertices or
v < 0 or v >= self.vertices) :
return

#  Display graph nodes and edges
def printGraph(self) :
print("\n Graph Adjacency List ", end = "")
i = 0
while (i < self.vertices) :
print(" \n [", i ,"] :", end = "", sep = "")
j = 0
#  iterate edges of i node
if (j != 0) :
print(" → ", end = "")

j += 1

i += 1

def main() :
matrix = [
[0, 1, 1, 0, 1],
[1, 0, 1, 0, 1],
[1, 1, 0, 1, 0],
[0, 1, 0, 0, 1],
[1, 1, 0, 1, 0]
]
g = Graph(matrix)
#  Display graph element
g.printGraph()

if __name__ == "__main__": main()``````

Output

`````` Graph Adjacency List
[0] : 1 →  2 →  4
[1] : 0 →  2 →  4
[2] : 0 →  1 →  3
[3] : 1 →  4
[4] : 0 →  1 →  3``````

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post