Java Program to do a Depth First Search/Traversal on a graph non-recursively

Problem Description

Given a graph in the form of an adjacency matrix and a source vertex, write a program to perform a depth-first search of the graph. In depth-first search traversal, neighbours of a node are traversed first.

Problem Solution

The idea is to store the source vertex in the stack. Now, iterate through the stack until it is empty. For every vertex retrieved from the stack, check which of its neighbours are still not processed. Traverse the first encountered neighbour after adding the current vertex to the stack.

Program/Source Code

Here is the source code of the Java Program to do a Depth First Search/Traversal on a graph non-recursively. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

//Java Program to do a Depth First Search/Traversal on a graph non-recursively
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
 
public class DepthFirstSearch {
    // Function to perform depth first search
    static void depthFirstSearch(int[][] matrix, int source){
        boolean[] visited = new boolean[matrix.length];
        visited[source-1] = true;
        Stack<Integer> stack = new Stack<>();
        stack.push(source);
        int i,x;
        System.out.println("The depth first order is");
        System.out.println(source);
        while(!stack.isEmpty()){
            x = stack.pop();
            for(i=0; i<matrix.length; i++){
                if(matrix[x-1][i] == 1 && visited[i] == false){
                    stack.push(x);
                    visited[i] = true;
                    System.out.println(i+1);
                    x = i+1;
                    i = -1;
                }
            }
        }
    }
    // Function to read user input
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int vertices;
        System.out.println("Enter the number of vertices in the graph");
        try{
            vertices = Integer.parseInt(br.readLine());
        }catch(IOException e){
            System.out.println("An error occurred");
            return;
        }
        int[][] matrix = new int[vertices][vertices];
        System.out.println("Enter the adjacency matrix");
        int i,j;
        for(i=0; i<vertices; i++){
            for(j=0; j<vertices; j++){
                try{
                    matrix[i][j] = Integer.parseInt(br.readLine());
                }catch (IOException e){
                    System.out.println("An error occurred");
                }
            }
        }
        int source;
        System.out.println("Enter the source vertex");
        try{
            source = Integer.parseInt(br.readLine());
        }catch(IOException e){
            System.out.println("An error occurred");
            return;
        }
        depthFirstSearch(matrix,source);
    }
}

Program Explanation

1. In function depthFirstSearch(), a boolean array is created and visited value of the source is set to true.
2. Then a stack is created and source vertex is added to it.
3. The loop while(!stack.isEmpty()) traverses until the stack is empty.
4. The nested loop for(i=0; i&ltmatrix.length; i++) traverses through all the neighbours of the currently popped vertex from the stack.
5. The condition if(matrix[x-1][i] == 1 && visited[i] == false) looks for all the neighbours of the currently polled vertex and traverses the first non-visited neighbour after pushing the current vertex to the stack.

Time Complexity: O(n2) where n is the number of elements in the array.

Runtime Test Cases

Case 1 (Simple Test Case):
 
Enter the number of vertices in the graph
4
Enter the adjacency matrix
1
1
1
1
1
0
0
0
1
1
1
0
0
0
0
1
Enter the source vertex
2
The depth first order is
2
1
3
4
 
Case 2 (Simple Test Case - another example):
 
Enter the number of vertices in the graph
3
Enter the adjacency matrix
0
0
0
1
0
1
1
1
1
Enter the source vertex
3
The depth first order is
3
1
2

Related posts:

Object cloning trong java
Java Program to Implement Ternary Tree
Từ khóa this và super trong Java
An Intro to Spring Cloud Contract
Java Program to Implement LinkedBlockingDeque API
Java Program to Implement Bellman-Ford Algorithm
Lập trình mạng với java
Login For a Spring Web App – Error Handling and Localization
Java Program to Implement Bit Array
Quick Guide on Loading Initial Data with Spring Boot
Spring Data JPA @Query
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Java Program to Use rand and srand Functions
Spring Security Login Page with React
Java 8 Collectors toMap
REST Web service: Upload và Download file với Jersey 2.x
Spring Boot - OAuth2 with JWT
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to implement Bit Set
Introduction to Netflix Archaius with Spring Cloud
Java Program to Implement Pollard Rho Algorithm
Calling Stored Procedures from Spring Data JPA Repositories
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Handling URL Encoded Form Data in Spring REST
Java Program to Implement Hash Tables chaining with Singly Linked Lists
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Hướng dẫn sử dụng lớp Console trong java
Java Program to implement Bi Directional Map
Spring Boot - Tomcat Deployment
Java Program to Find the Longest Path in a DAG
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Java Program to Perform String Matching Using String Library