jbn6972

Untitled

May 11th, 2022 (edited)
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. import sys
  2. from collections import defaultdict
  3. import os
  4. try:
  5.     sys.stdin = open('./input.txt', 'r')
  6.     sys.stdout = open('./output.txt', 'w')
  7. except:
  8.     pass
  9.  
  10.  
  11. class Graph:
  12.     def __init__(self):
  13.         self.graph = defaultdict(list)
  14.         self.parent = [-1 ]*9
  15.  
  16.  
  17.     def addEdge(self,u,v):
  18.         self.graph[u].append(v)
  19.  
  20.     def find_path(self,goal):
  21.         print("Goal Node Found!!")
  22.         print("Path traced : ")
  23.         node = goal
  24.         while node != 0:
  25.             print(node,end=",")
  26.             node = self.parent[node]
  27.         print(0)
  28.  
  29.     def DFS(self,source,goal):
  30.         self.parent[source] = source
  31.         visited = []
  32.         stack = []
  33.  
  34.         stack.append(source)
  35.  
  36.         while stack:
  37.             # print(self.parent)
  38.             top = stack.pop(0)
  39.             if top == goal:
  40.                 self.find_path(top)
  41.                 return
  42.             print(top,end=",")
  43.             children_top = self.graph[top]
  44.             children = []
  45.             for child in children_top:
  46.                 if child not in stack and child not in visited:
  47.                     self.parent[child] = top
  48.                     children.append(child)
  49.             stack = children+stack
  50.             # print(stack)
  51.             visited.append(top)
  52.  
  53.         print("Goal node not present")
  54.  
  55.  
  56. DFS_Graph = Graph()
  57. DFS_Graph.addEdge(0,1)
  58. DFS_Graph.addEdge(0,2)
  59. DFS_Graph.addEdge(0,3)
  60. DFS_Graph.addEdge(2,4)
  61. DFS_Graph.addEdge(3,5)
  62. DFS_Graph.addEdge(3,6)
  63. DFS_Graph.addEdge(4,5)
  64. DFS_Graph.addEdge(4,7)
  65. DFS_Graph.addEdge(5,3)
  66. DFS_Graph.addEdge(7,8)
  67. # print(DFS_Graph.graph)
  68.  
  69.  
  70.  
  71. DFS_Graph.DFS(0,5)
Add Comment
Please, Sign In to add comment