-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
32 lines (27 loc) · 681 Bytes
/
Copy pathdfs.py
File metadata and controls
32 lines (27 loc) · 681 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from collections import defaultdict
visited = []
def dfs(visited, graph, node):
if node not in visited:
print(node, end=" ")
visited.append(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# graph = {
# '5': ['3', '7'],
# '3': ['2', '4'],
# '7': ['8'],
# '2': [],
# '4': ['8'],
# '8': []
# }
graph = defaultdict(list)
n = int(input("Enter no. of edges : "))
for i in range(n):
u = int(input())
v = int(input())
graph[u].append(v)
print('Graph : ', dict(graph))
start = int(input("Enter start node : "))
print()
print("Following is the Depth-First Search")
dfs(visited, graph, start)