You are on page 1of 9

Introduction to DFS

What is DFS?

DFS stands for Depth-First Search. It is an algorithm used to traverse or search through a graph
or tree data structure. The algorithm starts at a given node and explores as far as possible along
each branch before backtracking.

Purpose of DFS

DFS is commonly used to:

 Traverse or search a graph or tree data structure


 Find connected components or cycles in a graph
 Determine if a path exists between two nodes
 Generate a topological sorting of a directed acyclic graph (DAG)
 Solve puzzles and mazes
 Perform graph coloring
 Conduct network analysis and routing

DFS Algorithm
Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along
each branch before backtracking. It can be implemented using recursion or a stack. The steps
involved in the DFS algorithm are as follows:

1. Start at a given vertex, called the 'start vertex'.


2. Mark the start vertex as visited.
3. Explore an unvisited neighbor of the start vertex.
4. If there are no unvisited neighbors, backtrack to the previous vertex and explore its
unvisited neighbors.
5. Repeat steps 3 and 4 until all vertices have been visited or there are no more unvisited
neighbors to explore

DFS in Maze Solving


DFS (Depth-First Search) is a graph traversal algorithm that can be used to solve mazes and find
a path from the start to the end.

The basic idea of DFS is to explore as far as possible along each branch before backtracking. In
the context of maze solving, DFS starts at the entrance of the maze and explores each possible
path until it finds a solution or exhausts all possibilities.

DFS is particularly useful in maze solving because it can find a solution quickly if there is one,
and it does not require any additional memory beyond the stack used for recursion.
Here is a step-by-step explanation of how DFS can be used to solve a maze:

1. Start at the entrance of the maze.


2. Mark the current position as visited.
3. Explore each neighboring cell that has not been visited.
4. If a neighboring cell leads to the exit, the maze has been solved.
5. If a neighboring cell does not lead to the exit, recursively apply DFS to that cell.
6. Backtrack if all neighboring cells have been visited or do not lead to the exit.
7. Repeat steps 3-6 until the exit is found or all paths have been explored.

By following this process, DFS can systematically explore the maze and find a path from the
start to the end.

DFS in Backtracking
Definition

Depth-first search (DFS) is a graph traversal algorithm that explores as far as possible along each
branch before backtracking.

Application in Backtracking

DFS is commonly used in backtracking algorithms to find solutions to problems. Backtracking is


an algorithmic technique that explores all possible solutions by incrementally building a solution
and undoing the choices that lead to a dead end.

How DFS is Used in Backtracking

DFS is used in backtracking algorithms to explore all possible paths or solutions by recursively
visiting each node in a graph or tree. It starts at the root node and explores as far as possible
along each branch before backtracking to the previous node and exploring other branches.

Example

For example, in the N-Queens problem, DFS is used in the backtracking algorithm to find all
possible configurations of placing N queens on an NxN chessboard such that no two queens
threaten each other.

https://www.geeksforgeeks.org/applications-of-depth-first-search/

ad/des/app
Depth First Search (DFS) is a graph traversal algorithm that visits all the nodes of a graph or tree by
exploring as far as possible along each branch before backtracking. It starts from a given node and
traverses the graph in a depth-first manner, meaning it first visits the deepest nodes and then
backtracks to visit other nodes.

In this mathematics article, we will cover the various aspects of the Depth First Search (DFS)
algorithm such as its purpose, how it works, and its advantages & disadvantages. By the end of the
article, the reader should have a clear idea of the underlying concepts and the mechanics of the DFS
algorithm.

Depth First Search


Depth First Search (DFS) is a common graph traversal algorithm that explores the depth of a graph,
i.e., it goes as far as possible along each branch before backtracking. It can be used to search for
paths, cycles, or connected components in a graph.

A recursive algorithm is employed to explore all the vertices in a tree data structure or graph through
the depth-first search (DFS) method. Starting from the initial node of graph G, the DFS algorithm
delves deeper until either the goal node or a node with no children is encountered. As the DFS
algorithm is recursive in nature, a stack data structure can be utilized to implement it. The process of
implementing DFS is same to the BFS algorithm.

In the below search tree, we have shown the flow of depth-first search, and it will follow the order as:

Root node ---> Left node ----> Right node.

The search process will commence from the root node S� and follow a path to
nodes A�, B�, D�, and E�. Once it reaches E�, the search will backtrack since E� has no other
successors, and the goal node has not yet been found. After backtracking, the search will continue to
traverse node C�, then G�, and terminate once it reaches the goal node.
To learn about the faces, edges and vertices for different shapes with examples.

Depth First Search Algorithm


The Depth First Search (DFS) algorithm is a recursive algorithm that is used to traverse or search for
nodes in a graph or a tree data structure. The algorithm begins at a specific node of the graph and
explores as far as possible in a single branch before backtracking.

The steps involved in the DFS algorithm are as follows:

o Begin by creating a stack with a capacity equal to the total number of vertices in the graph.
o Select any vertex as the starting point of traversal and add it to the top of the stack.
o Look for a non-visited vertex that is adjacent to the vertex on the top of the stack and push it
onto the top of the stack.
o Repeat steps 3 and 4 until there are no remaining unvisited vertices connected to the vertex
on the top of the stack.
o If there are no vertices left, backtrack by popping the vertex from the top of the stack.
o Repeat steps 2, 3, and 4 until the stack becomes empty.

Below is the implementation of the above approach:

# Python3 program to print DFS traversal from a given graph

from collections import defaultdict

# This class represents a directed graph using adjacency list representation

class Graph:

# Constructor

def __init__(self):

# default dictionary to store graph

self.graph = defaultdict(list)

# function to add an edge to graph

def addEdge(self, u, v):

self.graph[u].append(v)
# A function used by DFS

def DFSUtil(self, v, visited):

# Mark the current node as visited and print it

visited.add(v)

print(v, end=' ')

# Recur for all the vertices adjacent to this vertex

for neighbour in self.graph[v]:

if neighbour not in visited:

self.DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses recursive DFSUtil()

def DFS(self, v):

# Create a set to store visited vertices

visited = set()

# Call the recursive helper function to print DFS traversal

self.DFSUtil(v, visited)

# Driver's code

# Create a graph given in the above diagram

if __name__ == "__main__":

g = Graph()

g.addEdge(0, 1)

g.addEdge(0, 2)

g.addEdge(1, 2)

g.addEdge(2, 0)
g.addEdge(2, 3)

g.addEdge(3, 3)

print(“Following is DFS from (starting from vertex 2)”)

# Function call

g.DFS(2)

Output of the program:

Following is Depth First Traversal (starting from vertex 22)


22 00 33 11

The DFS algorithm is useful in many applications, such as finding a path between two vertices in a
graph, detecting cycles in a graph, and testing whether a graph is connected. However, it is
important to note that the DFS algorithm may not necessarily find the shortest path between two
vertices, and it may not always visit all the nodes in a graph.

To learn about the different types of graphs in graph theory, their subgraphs, properties with
examples.

Time Complexity of Depth First Search


The time complexity of Depth First Search (DFS) algorithm depends on the data structure used to
implement the algorithm, the number of nodes in the graph or tree being traversed, and the number
of edges.

In the worst-case scenario, where the graph or tree is densely connected, i.e., there are many edges,
and the algorithm visits all nodes in the graph or tree. The time complexity of DFS
is O(V+E)�(�+�), where V� is the number of vertices/nodes, and E� is the number of edges in
the graph.
In the case of a sparse graph, where there are relatively fewer edges than nodes, the time complexity
of DFS reduces to O(Vlog(V))�(�log⁡(�)).
In general, the time complexity of DFS is linear in the number of nodes and edges in the graph or
tree being traversed. However, the performance of the algorithm can be improved by using efficient
data structures, such as a binary heap or Fibonacci heap, to implement the algorithm.

Difference Between Depth First Search and Breadth


First Search
Depth First Search (DFS) and Breadth First Search (BFS) are two popular algorithms used for
traversing or searching through a graph or a tree data structure.
DFS visits all the vertices along a path from the starting vertex as far as possible before backtracking,
while BFS visits all the vertices at a given level before moving to the next level. Here are some of the
key differences between DFS and BFS.

Parameter Depth First Search Breadth First Search


Search Order DFS visits vertices in the order of their BFS visits vertices in the order of their
depth from the source vertex. distance from the source vertex.
Memory DFS uses a stack (or recursion) to store BFS uses a queue to store the vertices,
Usage the vertices, and hence uses less memory and hence requires more memory than
than BFS. DFS.
Completeness DFS may not find the shortest path, and BFS is guaranteed to find the shortest
may get stuck in an infinite loop if the path between the source and any other
graph has cycles. vertex in an unweighted graph.
Time Time complexity of DFS Time complexity of BFS
Complexity is O(V+E)�(�+�), where V� is the is O(V+E)�(�+�), where V� is
number of vertices and E� is the number the number of vertices and E� is the
of edges in the graph. number of edges in the graph.
In summary, DFS is useful when memory usage is a concern or when finding any path between two
vertices is sufficient, while BFS is a good choice when the shortest path is needed.

Application of Depth First Search


Depth First Search (DFS) is a popular algorithm used in computer science to traverse and search
through a graph or tree structure. Here are some common applications of DFS:

o Finding connected components: DFS can be used to identify all the connected components
in an undirected graph.
o Cycle detection: DFS can be used to detect cycles in a graph. If a node is visited again
during a DFS traversal, it indicates that there is a cycle in the graph.
o Topological sorting: DFS can be used to perform topological sorting on a directed acyclic
graph (DAG). In topological sorting, the nodes of a graph are ordered in such a way that for
every directed edge from node A to node B, node A comes before node B in the ordering.
o Pathfinding: DFS can be used to find a path between two nodes in a graph.
o Solving puzzles: DFS can be used to solve puzzles such as mazes, where the goal is to find a
path from the start to the end.
o Spanning trees: DFS can be used to construct a spanning tree of a graph. A spanning tree is
a subgraph of a connected graph that includes all the vertices of the original graph and is
also a tree.
o Backtracking: DFS can be used for backtracking in algorithms like the N-Queens problem or
Sudoku.

To learn about the distance between points, their formula and derivation with examples.

Advantages of Depth First Search


o In contrast to Breadth-First Search that requires more memory, Depth-First Search uses a
memory allocation proportional to the search graph's size. This is because DFS only requires
a stack of nodes that represent the current path from the root to the current node.
o Since Depth-First Search produces the same set of nodes as Breadth-First Search, but in a
distinct order, the time complexity of DFS to depth ‘ d�’ and branching factor ‘b�’ (the
number of children at each node) is O(bd)�(��). Consequently, DFS is often time-limited
rather than space-limited in practice.
o When Depth-First Search discovers a solution by exploring only a small portion of the search
space, the time and space required to find the solution will be minimal.
o DFS utilizes less memory as it only stores the nodes on the current path. There is a possibility
that DFS may encounter a solution without having to examine much of the search space.

To learn about undirected graphs, their applications, difference between directed and undirected
graphs with examples.

Disadvantages of Depth First Search


o DFS can be disadvantageous because it may become stuck traversing the left-most path
indefinitely, even if the graph is finite, resulting in an infinite tree. A possible solution to this
problem is setting a cutoff depth on the search, but determining the ideal depth, which is the
solution depth, is often challenging. Selecting a depth lower than d� would cause the
algorithm to fail to find a solution, while choosing a higher depth than d� would increase
execution time significantly and may not yield the optimal solution.
o Depth-First Search is not guaranteed to find the solution and there is no guarantee to find a
minimal solution, if more than one solution.

To learn about connectivity in graph theory with solved problems.

Depth First Search Solved Examples


1. What is the space complexity of depth first search?

Solution:

The space complexity of depth first search (DFS) is O(h)�(ℎ), where hℎ is the maximum depth of the
search tree.

o DFS stores only the nodes on the current path from the root to the current node being
explored. Once all children of a node have been explored, it removes the node from memory,
which allows it to explore other branches.
o In the worst case, if the tree is a linear chain, the maximum depth hℎ would be equal to the
number of nodes n� in the tree, resulting in a space complexity of O(n)�(�). However, if
the tree is balanced, with a height of log(n)log⁡(�), then the space complexity would
be O(log(n))�(log⁡(�)).
Overall, DFS is generally efficient in terms of space complexity, making it useful for exploring large
search trees or graphs with limited memory.

2. Finding connected components in an undirected graph. Suppose we have the following


undirected graph:

Solution:

We can use DFS to find the connected components of the graph. Starting at node 11, we explore all
its neighbors recursively until we have visited all nodes in the first connected component (1,2,4,5)
(1,2,4,5). Then, we backtrack to node 33, which is unexplored, and explore its neighbors (6)(6). We
continue this process until all nodes in the graph have been visited.
We hope that the above article is helpful for your understanding and exam preparations.Stay tuned
to the Testbook App for more updates on related topics from Mathematics, and various such
subjects. Also, reach out to the test series available to examine your knowledge regarding several
exams.
https://testbook.com/maths/depth-first-search

You might also like