Posted on by Kalkicode
Code Graph

Construct adjacency list by using adjacency matrix in python

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

#    Python 3 program for
#    Construct adjacency list using adjacency matrix
class Graph :
	def __init__(self, matrix) :
		#  Set number of nodes
		self.vertices = len(matrix)
		self.adgeList = []
		i = 0
		#  Create memory of adgeList of each vertice
		while (i < self.vertices) :
			self.adgeList.append([])
			i += 1
		
		self.makeAdjacencyList(matrix)
	
	#  Convert into adjacency list
	def makeAdjacencyList(self, matrix) :
		i = 0
		while (i < self.vertices) :
			j = 0
			while (j < self.vertices) :
				if (matrix[i][j] == 1) :
					self.addEdge(i, j)
				
				j += 1
			
			i += 1
		
	
	def addEdge(self, u, v) :
		if (u < 0 or u >= self.vertices or 
            v < 0 or v >= self.vertices) :
			return
		
		#  Add node edge
		self.adgeList[u].append(v)
	
	#  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
			while (j < len(self.adgeList[i])) :
				if (j != 0) :
					print(" → ", end = "")
				
				print("", self.adgeList[i][j], 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.

New Comment