-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
55 lines (47 loc) · 1.18 KB
/
dfs.py
File metadata and controls
55 lines (47 loc) · 1.18 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
# def dfs(node,graph):
# visited = set()
# if node not in graph:
# print('Node is not present in graph')
# return
# stack = []
# stack.append(node)
# while stack:
# current = stack.pop()
# if current not in visited:
# print(current)
# visited.add(current)
# for i in graph[current]:
# stack.append(i)
# graph = {'0': ['1', '2'],
# '1': ['0', '3', '4'],
# '2': ['0'],
# '3': ['1'],
# '4': ['2', '3']
# }
# graph = {'0': set(['1', '2']),
# '1': set(['0', '3', '4']),
# '2': set(['0']),
# '3': set(['1']),
# '4': set(['2', '3'])}
# print(graph)
# print("DFS traversal of Graph is : ")
# dfs('0',graph)
def dfs(graph, node, visited):
if node not in visited:
visited.append(node)
for k in graph[node]:
dfs(graph,k, visited)
return visited
graph= {
'A' : ['B','C'],
'B' : ['D','E','A'],
'C' : ['F','G','A'],
'D' : [],
'E' : [],
'F' : [],
'G' : []
}
visited = dfs(graph,'A', [])
print(graph)
print('DFS of above graph is : ')
print(visited)