-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS_DFS.py
More file actions
45 lines (33 loc) · 688 Bytes
/
BFS_DFS.py
File metadata and controls
45 lines (33 loc) · 688 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
43
44
from collections import deque
def dfs(graph, v , visited):
visited[v] = True
print(v, end=' ')
for i in graph[v]:
if not visited[i]:
dfs(graph, i, visited)
def bfs(graph, start, visited):
queue = deque([start])
visited[start] = True
while queue:
v = queue.popleft()
print(v,end=' ')
for i in graph[v]:
if not visited[i]:
queue.append(i)
visited[i] = True
graph = [
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
visited = [False]*9
bfs(graph, 1, visited)
visited = [False]*9
dfs(graph, 1, visited)
print("\n")