Advertisement
jbn6972

Untitled

Aug 28th, 2022 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. #Code Written by : John Nixon
  2. #Date: 28:08:2022  Time: 11:14:09
  3. #Copyrights are applicable
  4.  
  5. import sys
  6. import os
  7. sys.setrecursionlimit(10000)
  8. try:
  9.     sys.stdin = open('./input.txt', 'r')
  10.     sys.stdout = open('./output.txt', 'w')
  11. except:
  12.     pass
  13.  
  14. class Graph:
  15.     def __init__(self,n):
  16.         self.directedGraph = []
  17.         self.n = n
  18.         self.undirectedGraph = []
  19.  
  20.     def addAdjMatrixRow(self,row):
  21.         self.directedGraph.append(row)
  22.  
  23.     def makeSymmetricMatrix(self):
  24.         self.undirectedGraph = [[0 for _ in range(len(self.directedGraph))] for _ in range(len(self.directedGraph))]
  25.  
  26.         for i in range(len(self.directedGraph)):
  27.             for j in range(len(self.directedGraph)):
  28.                 self.undirectedGraph[i][j] = self.undirectedGraph[j][i] = max(self.directedGraph[i][j] , self.directedGraph[j][i])
  29.  
  30.     def displayGraph(self,graph):
  31.         for row in graph:
  32.             print(row)
  33.  
  34.     def printPaths(self,u,dest,visited,path,graph):
  35.         visited[u] = True
  36.         path.append(u)
  37.  
  38.         if u == dest and len(path) == self.n:
  39.             print(path)
  40.         else:
  41.             for i in range (len(graph)):
  42.                 if not visited[i] and graph[u][i] == 1:
  43.                     self.printPaths(i,dest,visited,path,graph)
  44.        
  45.         path.pop()
  46.         visited[u] = False
  47.  
  48.     def printAllPaths(self,src,dest,graph):
  49.         visited = [False]*len(self.directedGraph)
  50.  
  51.         path = []
  52.  
  53.         self.printPaths(src,dest,visited,path,graph)
  54.  
  55. n = int(input())
  56. graph = Graph(n)
  57.  
  58. row = list(map(int,input().split()))
  59. graph.addAdjMatrixRow(row)
  60.  
  61. nodes = len(row)
  62.  
  63. for _ in range(nodes-1):
  64.     row = list(map(int,input().split()))
  65.     graph.addAdjMatrixRow(row)
  66.  
  67. graph.makeSymmetricMatrix()
  68. source,dest = map(int,input().split())
  69.  
  70. print("Directed Graph :: ")
  71. graph.displayGraph(graph.directedGraph)
  72. print()
  73. print("All Paths of lenght ",n)
  74. graph.printAllPaths(source,dest,graph.directedGraph)
  75. print()
  76. print("UnDirected Graph :: ")
  77. graph.displayGraph(graph.undirectedGraph)
  78. print()
  79. print("All Paths of lenght ",n)
  80. graph.printAllPaths(source,dest,graph.undirectedGraph)
  81.  
  82.  
  83.  
  84.  
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement