Depth First Search
Aim: Write a program to implement the Depth First Search algorithm
Theory:
DFS in AI stands for "Depth-First Search." It is a fundamental search algorithm used in artificial
intelligence (AI) and computer science for traversing and searching tree and graph structures.
DFS is a methodical and systematic way to explore the depths of a search tree or graph.
Working and Applications of DFS in AI:
1. Search Algorithm: DFS is primarily used for searching and exploring nodes or states in a tree
or graph data structure. In AI, these nodes often represent different states or configurations of a
problem, such as puzzle states in games or possible paths in a navigation system.
2. Exploration Strategy: DFS explores the search space by moving as far down a branch of the
search tree as possible before backtracking. It starts at the initial state and explores one branch as
deeply as possible before returning to the previous node and exploring the next branch.
3. Stack-Based: DFS uses a stack data structure to manage the order in which nodes are explored.
When a node is explored, its child nodes are pushed onto the stack, and the algorithm continues
to explore the child nodes until it reaches a leaf node (a node with no unexplored children). It
then backtracks by popping nodes from the stack.
4. Completeness: DFS may not be complete in all cases, especially if the search space is infinite
or contains cycles. It can get stuck in infinite loops if not properly modified or used with
precautions.
5. Memory Usage: DFS can be memory-intensive, especially in deep search trees or graphs. It
stores all unexplored nodes on the stack, which can lead to high memory usage.
Applications in AI:
DFS has several applications in artificial intelligence and related fields:
1. Search Problems: DFS is used to search for solutions to problems in AI, such as finding a path
in a maze, solving puzzles like the Eight-Puzzle or Rubik's Cube, and planning in robotics.
2. Game Playing: DFS can be employed in game-playing AI to explore possible moves and find
the best move in games with relatively small state spaces, such as chess.
3. Parsing and Tree Traversal: In natural language processing and syntax analysis, DFS is used to
parse sentences and traverse parse trees.
4. Algorithm Design: DFS is a key component in various AI algorithms and techniques, such as
depth-limited search, iterative deepening, and backtracking.
5. Topological Sorting: DFS can be used to perform topological sorting of directed acyclic
graphs, which is useful in scheduling and dependency resolution problems.
6. Maze Solving: In robotics and pathfinding applications, DFS can be used to find a path
through a maze or grid.
In summary, Depth-First Search (DFS) is an essential algorithm in AI and computer science for
systematically exploring tree and graph structures. It is particularly useful for problems where
deep exploration is needed and where memory constraints are not a significant concern.
However, it should be used with caution in cases where completeness is essential, especially in
graphs with cycles.
Code:
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)
# Example graph (adjacency list)
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
# Create an empty set to store visited nodes
visited = set()
# Call DFS starting from node 'A'
print("Depth First Search Traversal:")
dfs(graph, 'A', visited)
Output:
Depth First Search Traversal:
ABDEFC
This Python program performs a Depth First Search (DFS) traversal on a graph represented
using an adjacency list (a dictionary). The function dfs(graph, node, visited) starts from a given
node and explores as far as possible along each branch before backtracking. It first checks if the
current node has already been visited to avoid revisiting nodes. If not, it prints the node and
marks it as visited by adding it to the visited set. Then, it recursively visits each neighbor of the
current node. The graph is defined as a dictionary where each key is a node, and its value is a list
of connected nodes. The traversal begins from node 'A', and the visited set ensures that each
node is processed only once, preventing infinite loops. As a result, the DFS traversal order is
printed as: A B D E F C. This code demonstrates the basic concept of DFS using recursion and is
a useful technique for traversing or searching tree or graph structures.
A
/\
B C
/\ \
D E F
\
F
Step Node Visited Visited Set
1 A {A}
2 B {A, B}
3 D {A, B, D}
4 E {A, B, D, E}
5 F {A, B, D, E, F}
6 C {A, B, D, E, F, C}
Difference between BFS and DFS
Feature BFS (Breadth-First Search) DFS (Depth-First Search)
Level by level (explores neighbors Depth-wise (explores as deep as
Traversal Method
first) possible first)
Data Structure Used Queue Stack (or recursion)
Begins at a node and explores all its Begins at a node and goes deep
Starting Point
neighbors first before backtracking
Nodes closer to the source are Nodes farther from the source may
Visited Order
visited earlier be visited earlier
Feature BFS (Breadth-First Search) DFS (Depth-First Search)
Finding shortest path in unweighted Topological sorting, cycle
Used For
graphs, level order detection, maze solving
More memory (stores all neighbors Less memory (only the path being
Memory Usage
in the queue) explored is stored)
Implementation Slightly more complex due to queue
Simpler using recursion
Simplicity management
For graph A→B, A→C → BFS: A For graph A→B, A→C → DFS: A
Example Traversal
BC BDEFC
Use BFS when you need the shortest path or level-order traversal.
Use DFS when you want to explore deeply, solve puzzles, or search entire paths.