This repository has been archived by the owner on Aug 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfsdfs.py
51 lines (40 loc) · 1.71 KB
/
bfsdfs.py
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
from collections import deque # double-ended queue
# fnc bfs
def bfs(graph, start):
visited = set() # empty set to keep track of the visited vertices during traversal.
queue = deque([start]) # deque object called queue, initialized with the start vertex.
# queue used to store the vertices to visit
while queue:
vertex = queue.popleft() # remove and return leftmost vertex from queue.
# check if the vertex has not been visited before and visit each vertex only once
if vertex not in visited:
print(vertex)
visited.add(vertex) # marks visited vertex
queue.extend(graph[vertex] - visited) # extend queue adding all neighbors of vertex not visited yet
# ensure only unvisited neighbors are added to the queue.
# fnc dfs; optional visited set that defaults to None
def dfs(graph, start, visited=None):
# check if visited set has not been provided as an argument and to create new empty set
if visited is None:
visited = set()
visited.add(start) # mark visited vertices
print(start)
# iterate over the neighbors of start vertex not visited yet.
# calculate set difference between neighbors of start and visited,
# ensuring that only unvisited neighbors are traversed.
for neighbor in graph[start] - visited:
# recursively call dfs function with neighbor as new start vertex and visited set
dfs(graph, neighbor, visited)
# Example graph represented as an adjacency list
graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}
print("BFS traversal:")
bfs(graph, 'A')
print("\nDFS traversal:")
dfs(graph, 'A')