Exploring Depth First Search (DFS)
Introduction
Depth-First Search (DFS) is a fundamental graph traversal algorithm used in many computer science applications. It explores as far as possible along each branch before backtracking, making it an excellent choice for problems that require exhaustive search of all possible paths or configurations
How DFS Works
DFS starts at a chosen node (root in the case of trees) and explores each branch as deeply as possible before moving on to the next branch. This is typically implemented using recursion or a stack.
Pseudocode for DFS :
Recursive Implementation :
def dfs_recursive(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start) # Process the node
for next in graph[start] - visited:
dfs_recursive(graph, next, visited)
return visited
Application of DFS :
Complexity :
Exploring Best First Search (BFS)
Introduction
Breadth-First Search (BFS) is another fundamental graph traversal algorithm widely used in computer science. Unlike DFS, BFS explores all neighbors at the present depth prior to moving on to nodes at the next depth level.
How BFS Works
BFS starts at the chosen node (root in trees) and explores all its neighbors first, then moves on to the neighbors of those neighbors, and so on. This approach ensures that the algorithm visits nodes in layers or levels.
Pseudocode for BFS :
Iterative Implementation :
from collections import deque
def bfs(graph, start):
queue = set(), deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
print(vertex) # Process the node
queue.extend(graph[vertex] - visited)
return visited