Graph traversal means visiting all the nodes (vertices) in a graph in a systematic way. DFS and BFS are two fundamental graph traversal techniques used widely in computer science.
DFS explores as deep as possible along each branch before backtracking. It uses recursion or stack data structure.
def dfs(graph, node, visited):
if node not in visited:
print(node, end=' ')
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
# Usage Example
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
visited = set()
dfs(graph, 'A', visited)
BFS explores neighbor nodes level by level using a queue data structure, visiting all nodes at the current depth before going deeper.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# Usage Example
bfs(graph, 'A')