forked from codebasics/data-structures-algorithms-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
30 lines (21 loc) · 559 Bytes
/
dfs.py
File metadata and controls
30 lines (21 loc) · 559 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
# function for depth first search
def dfs(data, start, visited=set()):
# if not visited print it
if start not in visited:
print(start, end=" ")
visited.add(start)
for i in data[start] - visited:
# if not visited gi in depth of it
dfs(data, i, visited)
return
# sample data in dictionary form
data = {
'A': {'B'},
'B': {'A', 'C', 'D'},
'C': {'B', 'E'},
'D': {'B', 'E'},
'E': {'C', 'D', 'F'},
'F': {'E'}
}
if __name__ == '__main__':
dfs(data, 'A')