Coders Packet

Implementation of Depth-First-Search (DFS) algorithm using Java

By Abhishek Birendra Verma

In this tutorial, we will learn about the Depth-First-Search algorithm and we will also see the program to implement the Depth-First-Search algorithm using Java.


Depth-first search (DFS) is an algorithm for which is used for traversing a tree or graph. The algorithm starts at the root node (which can be any node in a graph) and it keeps exploring the same route/path until it reaches the leaf node and after reaching the leaf node it backtracks along the same path until it finds an unvisited node and then it starts traversing that node until it reaches the leaf node/dead-end/visited node. This process keeps repeating until all the nodes are visited.

Backtracking means that when you are moving forward and there are no more nodes to traverse along the current path then you move back on the same path to find new unvisited nodes to traverse. DFS uses a stack for this purpose to keep track of the nodes that are yet to be visited.

The Worst-Case Time Complexity of DFS is O(V+E) where V is the total number of vertices and E is the total number of edges. Please note that to avoid visiting the already visited nodes more than once, the algorithm uses a Boolean “visited “array.


import java.util.Scanner;
import java.util.Stack;
  public class DFS {

    public static void main(String[] args) {
      // TODO Auto-generated method stub
      Scanner sc=new Scanner(;
      Stack stack1=new Stack();
      System.out.print("Enter the total number of vertices in the graph: ");
      int vertices=sc.nextInt();
      boolean visited[]=new boolean[vertices];
      int adj[][]=new int[vertices][vertices],i,j,count=1,starting_vertex;
      System.out.println("Enter the elements of adjacency matrix: ");
      System.out.println("Enter 0 if Edge does not Exists\nEnter 1 if Edge exists");
      for(i=0;i<vertices;i++) {
        for(j=0;j<vertices;j++) {
          System.out.print("Enter Adj["+(i+1)+"]["+(j+1)+"]:");
      System.out.print("Enter the Starting vertex:");
      if(starting_vertex<0||starting_vertex>=vertices) {
        System.out.println("Incorect value!! Try again");
      //Putting the starting vertex into the stack	
      System.out.println("Depth First Search is:");
      while(!stack1.isEmpty()) {
        //Selecting the top node in the stack to visit it and explore as far as possible along the same path/branch
          for(j=0;j<adj.length;j++) {
            if(adj[i][j]!=0&&!visited[j]) {
              //Printing the node after visiting it
              if(count<vertices-1) {
          //As the node has been visited so removing it from the stack



Download project

Reviews Report

Submitted by Abhishek Birendra Verma (AbhishekVerma)

Download packets of source code on Coders Packet