Advertisement
ricky123ghfghfhg

help chey mowa

Jan 9th, 2022
414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. from collections import defaultdict
  2.  
  3.  
  4. class Graph:
  5.  
  6.  def init(self):
  7.   self.graph = defaultdict(list)
  8.  def add_edge(self, u: int, v: int):
  9.   self.graph[u].append(v)
  10.  
  11. def dfs_util(self, v, visited):
  12.  if v not in self.graph:
  13.     print("Invalid root node...")
  14.     return
  15.  visited.add(v)
  16.  print(v, end = " ")
  17.  
  18.  for neighbour in self.graph[v]:
  19.      if neighbour not in visited:
  20.       self.dfs_util(neighbour, visited)
  21. def dfs(self, v):
  22.  
  23.  
  24.  visited = set()
  25.  self.dfs_util(v, visited)
  26.  
  27. g = Graph()
  28. print("Enter no of edges: ")
  29. n = int(input())
  30. print("Enter edges in following format: vertex1 vertex2")
  31.  
  32. for i in range(n):
  33.     x, y = [int(m) for m in input().split()]
  34.     g.add_edge(x, y)
  35.  
  36. print("Enter the root node for the DFS traversal: ")
  37. root = int(input())
  38. print(f"Following is DFS from (starting from root {root}): ")
  39. g.dfs(root)
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46. #Program 2
  47. from collections import defaultdict
  48.  
  49.  
  50. class Graph:
  51.  
  52.     def init(self):
  53.       self.graph = defaultdict(list)
  54.  
  55. def add_edge(self, u: str, v: str):
  56.  self.graph[u].append(v)
  57.  
  58. def dfs_util(self, v, visited):
  59.  if v not in self.graph:
  60.     print("Invalid root node...")
  61.     return
  62.  visited.add(v)
  63.  print(v, end = " ")
  64.  
  65.  for neighbour in self.graph[v]:
  66.      if neighbour not in visited:
  67.       self.dfs_util(neighbour, visited)
  68.  
  69. def dfs(self, v):
  70.  visited = set()
  71.  self.dfs_util(v, visited)
  72.  
  73. g = Graph()
  74. print("Enter no of edges: ")
  75. n = int(input())
  76. print("Enter edges in following format: vertex1 vertex2")
  77.  
  78. for i in range(n):
  79.  x, y = input().split()
  80.  g.add_edge(x, y)
  81.  
  82. print("Enter the root node for the DFS traversal: ")
  83. root = input()
  84. print(f"Following is DFS from (starting from root {root}): ")
  85. g.dfs(root)
  86.  
  87.  
  88.  
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement