Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import defaultdict
- class Graph:
- def init(self):
- self.graph = defaultdict(list)
- def add_edge(self, u: int, v: int):
- self.graph[u].append(v)
- def dfs_util(self, v, visited):
- if v not in self.graph:
- print("Invalid root node...")
- return
- visited.add(v)
- print(v, end = " ")
- for neighbour in self.graph[v]:
- if neighbour not in visited:
- self.dfs_util(neighbour, visited)
- def dfs(self, v):
- visited = set()
- self.dfs_util(v, visited)
- g = Graph()
- print("Enter no of edges: ")
- n = int(input())
- print("Enter edges in following format: vertex1 vertex2")
- for i in range(n):
- x, y = [int(m) for m in input().split()]
- g.add_edge(x, y)
- print("Enter the root node for the DFS traversal: ")
- root = int(input())
- print(f"Following is DFS from (starting from root {root}): ")
- g.dfs(root)
- #Program 2
- from collections import defaultdict
- class Graph:
- def init(self):
- self.graph = defaultdict(list)
- def add_edge(self, u: str, v: str):
- self.graph[u].append(v)
- def dfs_util(self, v, visited):
- if v not in self.graph:
- print("Invalid root node...")
- return
- visited.add(v)
- print(v, end = " ")
- for neighbour in self.graph[v]:
- if neighbour not in visited:
- self.dfs_util(neighbour, visited)
- def dfs(self, v):
- visited = set()
- self.dfs_util(v, visited)
- g = Graph()
- print("Enter no of edges: ")
- n = int(input())
- print("Enter edges in following format: vertex1 vertex2")
- for i in range(n):
- x, y = input().split()
- g.add_edge(x, y)
- print("Enter the root node for the DFS traversal: ")
- root = input()
- print(f"Following is DFS from (starting from root {root}): ")
- g.dfs(root)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement