Breadth First Search
Breadth First Search
7 From A we have D as
unvisited adjacent
node. We mark it as
visited and enqueue it.
Code:
from collections import deque
while queue:
# Dequeue the front element
current = queue.popleft()
result.append(current) # Process the node (e.g., store it in the
result)
return result
# Example Graph
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# Perform BFS
start_node = 'A'
print("BFS Traversal:", bfs(graph, start_node))
Code:
def dfs(graph, start):
visited = set() # To keep track of visited nodes
stack = [] # Initialize an empty stack
result = [] # To store the DFS traversal order
while stack:
# Pop the top node from the stack
current = stack.pop()
return result
# Example Graph
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# Perform DFS
start_node = 'A'
print("DFS Traversal:", dfs(graph, start_node))