Understanding Depth First Search (DFS)

Reena Rote
4 min readNov 19, 2023

Depth First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It’s commonly used to explore and analyze the structure of graphs and trees. In this blog post, we’ll delve into the details of DFS, provide a Kotlin implementation, discuss its time complexity, explore some use cases, and list a few LeetCode problems that can be solved using DFS.

What is Depth First Search?

DFS is a systematic method for exploring all vertices and edges of a graph or tree. The algorithm starts at a selected node and explores as deeply as possible along each branch before backtracking. This means it explores a path as far as it can go before it retreats and explores another path.

How DFS Works?

Initialization:

  • Graph Representation:
    The graph is represented, typically using an adjacency list or adjacency matrix.
  • Visited Set:
    A set or array is maintained to keep track of visited vertices.

Starting Vertex:

  • Choose a Starting Vertex:
    The algorithm begins by selecting a starting vertex from which the traversal will commence.

Exploration:

  • Visit the Current Vertex:
    Mark the current vertex…

--

--