Create a Graph Data Structure.
Run the code here: https://repl.it/@VinitKhandelwal/Graph
OUTPUT
0:[1, 2]
1:[3, 2, 0]
2:[4, 1, 0]
3:[1, 4]
4:[3, 2, 5]
5:[4, 6]
6:[5]
Run the code here: https://repl.it/@VinitKhandelwal/Graph
class Graph:
def __init__(self):
self.numberOfNodes = 0
self.adjacentDict = {}
def addVertex(self, node):
self.adjacentDict[node] = []
self.numberOfNodes += 1
def addEdge(self, node1, node2):
self.adjacentDict[node1].append(node2)
self.adjacentDict[node2].append(node1)
def showConnections(self):
for key, value in self.adjacentDict.items():
print(f"{key}:{value}")
obj = Graph()
obj.addVertex(0)
obj.addVertex(1)
obj.addVertex(2)
obj.addVertex(3)
obj.addVertex(4)
obj.addVertex(5)
obj.addVertex(6)
obj.addEdge(3, 1)
obj.addEdge(3, 4)
obj.addEdge(4, 2)
obj.addEdge(4, 5)
obj.addEdge(1, 2)
obj.addEdge(1, 0)
obj.addEdge(0, 2)
obj.addEdge(5, 6)
obj.showConnections()
0:[1, 2]
1:[3, 2, 0]
2:[4, 1, 0]
3:[1, 4]
4:[3, 2, 5]
5:[4, 6]
6:[5]
Comments
Post a Comment