Depth First Search (DFS) for Artificial Intelligence (original) (raw)

Last Updated : 23 Jul, 2025

Depth-First Search (DFS) is a helpful method in artificial intelligence. It helps AI systems work better and faster. DFS gives useful ideas for solving problems and is used in many real-world AI tasks. This article provides insights about what DFS is, why it matters in AI, and where it’s used in practice.

What is a Depth-First Search in AI?

Depth-first search is a traversing algorithm used intree and graph-like data structures. It generally starts by exploring the deepest node in the frontier. Starting at the root node, the algorithm proceeds to search to the deepest level of the search tree until nodes with no successors are reached. Suppose the node with unexpanded successors is encountered then the search backtracks to the next deepest node to explore alternative paths.

DFS Working

Depth-first search (DFS) explores a graph by selecting a path and traversing it as deeply as possible before backtracking.

Depth-first search in AI-Geeksforgeeks

Search operation of the depth-first search

Key characteristics of DFS

In simple terms, the DFS algorithms in AI holds the power of extending the current path as deeply as possible before considering the other options.

Edge classes in a Depth-first search tree based on a spanning tree

edge-classes-in-dfs

Edge classes in DFS based on spanning tree

The edges of the depth-first search tree can be divided into four classes based on the spanning tree, they are

Depth First Search(DFS) Algorithm in Python

1. Initialization

The graph is stored as a dictionary (adjacency list).

Screenshot-2025-07-07-115536

Graph for this implementation

We also prepare:

Define the graph as an adjacency list

graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': [], 'F': [] }

visited = set() # To track visited nodes traversal_order = [] # To store DFS traversal result

`

2. Define the DFS Function

This is a recursive DFS function:

def dfs(node): if node not in visited: visited.add(node) # Mark node as visited traversal_order.append(node)

    for neighbor in graph[node]:     # Visit all neighbors
        dfs(neighbor)                

`

3. Start DFS Traversal from Node 'A'

We start DFS from node A. It will go as deep as possible before backtracking.

Python `

dfs('A')

`

4. Final Traversal Order

This prints the final DFS order of visited nodes in a depth-first manner.

Python `

print("\nFinal Traversal Order:") print(" → ".join(traversal_order))

`

**Output:

Final Traversal Order: A → B → D → E → C → F

**You can download the complete code from here.

Time complexity of DFS:

**1. Explicit Time Complexity

This time complexity arises because DFS traverses each vertex and edge exactly once in the worst-case scenario. This complexity is for explicit traversing of DFS without any repetition. The time complexity of DFS is commonly represented as

O(|V| + |E|)

Where:

**2. Implicit Time Complexity

This implicit time complexity is appropriate while considering the time complexity in terms of the number of nodes visited in the tree instead of the number of edges and vertices in a graph. For implicit traversing of DFS can be simply depicted as,

O(bd)

where:

**Space complexity of DFS

**1. Explicit Space Complexity

The space complexity of DFS is commonly represented as

O(|V|)

Where:

This is because DFS typically uses additional data structures like stack or recursion stack to keep track of visited vertices.

**2. Implicit Space Complexity

For an implicit search in a graph, DFS’s space complexity can be represented as follows:

O(bd)

where:

This space complexity is said to be considered when the space is required to store the nodes on the current path during the search.

DFS Implementation in Robotics Pathfinding

DFS can be used to find a path from a start node to a goal node in a maze or grid-based environment. The DFS algorithm systematically explores all possible paths from the start node, one branch at a time until it finds a path that leads to the goal. The below figures show the maze which contains the initial state of the robot, the obstacles, and the goal state. Here, the goal node is in the position of (0,5) where the robot needs to traverse through the maze to find the path to reach the goal.

Step 1: Define Maze dimensions and obstacles

We define a **maze_size representing the dimension of the maze, in our case, it's a 6x6 grid. A list of coordinates that represents the positions of obstacles within a maze is also specified. The robot is positioned at the initial state (0,0) and aims to reach the goal state (0,5).

Maze environment -Geeksforgeeks

Maze environment

**Maze dimensions and obstacles

Python `

Maze dimensions and obstacles

maze_size = 6 obstacles = [(0,1),(1,1),(3,2),(3,3),(3,4),(3,5),(0,4),(4,1),(4,2),(4,3)] start = (0,0) goal = (0,5)

`

Step 2: Define a is_valid function

The **is_valid function checks whether a given position of (x,y) is valid such that it inspects that it's within the bounds of the maze and not obstructed by any obstacles.

Python `

def is_valid(x,y): return 0 <= x < maze_size and 0 <= y < maze_size and (x,y) not in obstacles

`

In the below code, we define the dfs function to implement the DFS algorithm. It uses a stack to keep a record of the nodes it visits, and it iterates through each node that helps in exploring its neighbors recursively until it finds the goal node or it exhausts all possibilities.

def dfs (current, visited, path): x, y = current if current == goal: path.append(current) return True visited.add(current) moves = [(x-1,y), (x+1, y), (x, y-1), (x, y+1)] for move in moves: if is_valid(*move) and move not in visited: if dfs(move, visited, path): path.append(current) return True return False

`

Step 4: Call DFS function to find the path

Python `

#Call DFS function to find the path visited = set() path = [] if dfs(start, visited, path): path.reverse() print("Path found:") for position in path: print(position) else: print("No path found!")

`

**Output:

Path found:
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(2, 1)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(1, 3)
(2, 3)
(2, 4)
(1, 4)
(1, 5)
(0, 5)

**Output explanation

path-finding-in-dfs-final-output

Output representation

**You can download the complete code from here.

Applications of DFS in AI