Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Code Written by : John Nixon
- #Date: 28:08:2022 Time: 11:14:09
- #Copyrights are applicable
- import sys
- import os
- sys.setrecursionlimit(10000)
- try:
- sys.stdin = open('./input.txt', 'r')
- sys.stdout = open('./output.txt', 'w')
- except:
- pass
- class Graph:
- def __init__(self,n):
- self.directedGraph = []
- self.n = n
- self.undirectedGraph = []
- def addAdjMatrixRow(self,row):
- self.directedGraph.append(row)
- def makeSymmetricMatrix(self):
- self.undirectedGraph = [[0 for _ in range(len(self.directedGraph))] for _ in range(len(self.directedGraph))]
- for i in range(len(self.directedGraph)):
- for j in range(len(self.directedGraph)):
- self.undirectedGraph[i][j] = self.undirectedGraph[j][i] = max(self.directedGraph[i][j] , self.directedGraph[j][i])
- def displayGraph(self,graph):
- for row in graph:
- print(row)
- def printPaths(self,u,dest,visited,path,graph):
- visited[u] = True
- path.append(u)
- if u == dest and len(path) == self.n:
- print(path)
- else:
- for i in range (len(graph)):
- if not visited[i] and graph[u][i] == 1:
- self.printPaths(i,dest,visited,path,graph)
- path.pop()
- visited[u] = False
- def printAllPaths(self,src,dest,graph):
- visited = [False]*len(self.directedGraph)
- path = []
- self.printPaths(src,dest,visited,path,graph)
- n = int(input())
- graph = Graph(n)
- row = list(map(int,input().split()))
- graph.addAdjMatrixRow(row)
- nodes = len(row)
- for _ in range(nodes-1):
- row = list(map(int,input().split()))
- graph.addAdjMatrixRow(row)
- graph.makeSymmetricMatrix()
- source,dest = map(int,input().split())
- print("Directed Graph :: ")
- graph.displayGraph(graph.directedGraph)
- print()
- print("All Paths of lenght ",n)
- graph.printAllPaths(source,dest,graph.directedGraph)
- print()
- print("UnDirected Graph :: ")
- graph.displayGraph(graph.undirectedGraph)
- print()
- print("All Paths of lenght ",n)
- graph.printAllPaths(source,dest,graph.undirectedGraph)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement