BFS & DFS Theory
BFS & DFS Theory
BFS explores the graph level by level, starting from the source node and visiting all its neighbors first.
BFS(graph, start):
create a queue Q
mark start as visited
enqueue start into Q
• Queue
• Visited array or set
Time Complexity:
Applications:
DFS explores the graph deeply, going as far as possible along one path before backtracking.
DFS(graph, start):
mark start as visited
for each neighbor of start:
if neighbor not visited:
DFS(graph, neighbor)
A
• O(V + E) for adjacency list / \
• O(V²) for adjacency matrix B C
| \
Applications: D E
• BFS(A): A → B → C → D → E
• Cycle detection
• DFS(A): A → B → D → C → E
• Topological sorting
• Solving puzzles (e.g., mazes, Sudoku)
• Pathfinding in AI
Good for Shortest paths, AI, routing Puzzle solving, tree/graph analysis