-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdfs.py
More file actions
42 lines (36 loc) · 670 Bytes
/
dfs.py
File metadata and controls
42 lines (36 loc) · 670 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
33
34
35
36
37
38
39
40
41
42
from collections import defaultdict
'''
V E
FOR EVERY EDGE
U V
7 9
A B
A C
A F
C E
C F
C D
D E
D G
G F
'''
# T.C = O(V+E)
# S.C = O(V)
def dfs(graph,start,visited,path):
path.append(start)
visited[start] = True
for neighbour in graph[start]: # O(V+E)
if visited[neighbour] == False: # O(1)
dfs(graph,neighbour,visited,path)
return path
v,e = map(int,input().split())
graph = defaultdict(list)
for i in range(e):
u,v = map(str,input().split())
graph[u].append(v)
graph[v].append(u)
path = []
start = 'A'
visited = defaultdict(bool)
traversedpath = dfs(graph,start,visited,path)
print(traversedpath)