Adjacency list representation of undirected graph in python
Python program for Adjacency list representation of undirected graph. Here problem description and explanation.
# Python 3 Program for
# Undirected graph representation by using adjacency list
class AjlistNode :
# Vertices node key
def __init__(self, id) :
# Set value of node key
self.id = id
self.next = None
class Vertices :
def __init__(self, data) :
self.data = data
self.next = None
self.last = None
class Graph :
# Number of Vertices
def __init__(self, size) :
# Set value
self.size = size
self.node = [None] * (size)
self.setData()
# Set initial node value
def setData(self) :
if (self.size <= 0) :
print("\nEmpty Graph")
else :
index = 0
while (index < self.size) :
self.node[index] = Vertices(index)
index += 1
# Connect two nodes
def connect(self, start, last) :
edge = AjlistNode(last)
if (self.node[start].next == None) :
self.node[start].next = edge
else :
# Add edge at the end
self.node[start].last.next = edge
# Get last edge
self.node[start].last = edge
# Handling the request of adding new edge
def addEdge(self, start, last) :
if (start >= 0 and start < self.size and
last >= 0 and last < self.size) :
self.connect(start, last)
if (start == last) :
# When self loop
return
self.connect(last, start)
else :
# When invalid nodes
print("\nHere Something Wrong")
def printGraph(self) :
if (self.size > 0) :
index = 0
# Print graph ajlist Node value
while (index < self.size) :
print("\nAdjacency list of vertex ", index , end = " :")
temp = self.node[index].next
while (temp != None) :
# Display graph node
print(" ", self.node[temp.id].data, end = " ")
# Visit to next edge
temp = temp.next
index += 1
def main() :
# 5 implies the number of nodes in graph
g = Graph(5)
# Connect node with an edge
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(0, 4)
g.addEdge(1, 2)
g.addEdge(1, 4)
g.addEdge(2, 3)
g.addEdge(3, 4)
# print graph element
g.printGraph()
if __name__ == "__main__": main()
Output
Adjacency list of vertex 0 : 1 2 4
Adjacency list of vertex 1 : 0 2 4
Adjacency list of vertex 2 : 0 1 3
Adjacency list of vertex 3 : 2 4
Adjacency list of vertex 4 : 0 1 3
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