Depth First Search or DFS for a Graph in Java28 Mar 2025 | 4 min read For traversing or searching over graph structures, the basic method Depth First Search (DFS) is employed. It is a vital tool for many graph theory tasks, such as pathfinding, cycle detection, connection tests, and more, since it travels as far as feasible down each branch before turning around. DFS uses an implicit or explicit stack that is operated upon by recursion, implementing the last-in, first-out (LIFO) principle. We will examine the DFS algorithm, its Java implementation, and its modifications in this post. DFS Algorithm ExplanationThe DFS algorithm works as follows:
Let's implement the above algorithm in a Java program. File Name: DfsInGraph.java Output: Depth First Search starting from vertex 0: 0 1 3 4 2 5 ExplanationAn adjacency list is used by the Graph class to represent the graph. Every vertex possesses an array called LinkedList[] that contains a list of its neighbours. The addEdge() function creates edges connecting two vertices. Edges are added in both directions, from w to v and from vertex v to w, because we are working with an undirected graph. To keep track of which vertices have previously been visited, the DFS() function initialises a boolean array visited[]. The real recursive traversal is then handled by a helper function called DFSUtil().The current node is marked as visited and printed using the DFSUtil() function. Next, it investigates every one of the current node's unexplored neighbours recursively. Complexity AnalysisTime Complexity: Based on the number of vertices (V) and edges (E), the time complexity of DFS is O(V + E). This is a result of the traverse processing each vertex and edge once. Space Complexity: Because of the recursive call stack, the storage required for the visited[] array, the adjacency list, and other components, the space complexity is O(V). Applications of DFS
ConclusionDue to its recursive structure, it's very helpful for cases where you need to go back and look at every potential configuration. Comprehending DFS is essential for resolving a variety of graph-related computer science issues. This article explained the workings, applications, and complexity analysis of DFS and included a full Java implementation. Next TopicBig data Java vs Python |
Array Rotation in Java
In this section, we will learn what is rotation of an array and how to rotate an array in through a Java program. Java Array Rotation The rotation of an array simply means to shift the array elements of an array to the specified positions. We can rotate...
5 min read
Horizontal Flip Matrix Problem in Java
In the world of computer science and programming, matrix manipulation is a fundamental concept with applications in various domains, such as graphics, image processing, and scientific computations. One interesting and common matrix manipulation is the horizontal flip. In this section, we will discuss the horizontal...
5 min read
Java.util.function.LongPredicate interface in Java with Examples
JDK 8 introduces the IntPredicate interface. The package java.util.function contains this interface. It works with an integer value and, given a condition, returns a predicate value. It can also be utilized in lambda expression since it is a functional interface. The Methods are given by: 1. test():...
2 min read
Pattern Matching for Switch in Java 21
Pattern matching for switch expressions and statements is a feature introduced in Java 21 that allows developers to match specific patterns within switch cases, making code more concise and readable. To use pattern matching in a switch statement, we simply need to use the case keyword followed...
9 min read
Deprecated Meaning in Java
In the realm of software development, programming languages are constantly evolving to meet the demands of the industry. As new features are introduced and existing ones are improved, certain elements of the language may become outdated or considered less desirable. To address this, the Java programming...
3 min read
Write a Program to Print Reverse of a Vowels String in Java
In this section, we will be discussing how to print the reverse of a vowel string in Java. Vowels are the letters "a", "e", "i", "o", and "u", and a vowel string is a string that contains only vowels. We will first define the problem statement...
4 min read
Java Multicasting (Typecasting Multiple Times) Puzzle
Java multicasting, also known as typecasting multiple times, refers to the process of applying several typecasting operations sequentially on a variable. This often occurs in scenarios where data types are incompatible but need to be transformed to make the code functional. Multicasting is especially useful in object-oriented...
4 min read
Spring vs. Struts in Java
Spring and Struts are both popular Java frameworks used for developing web applications. Spring is a lightweight and flexible framework that provides a comprehensive solution for building enterprise-level applications. It offers dependency injection, aspect-oriented programming, and integration with Hibernate and JPA. Spring promotes a modular and...
2 min read
XOR Operation on Long in Java
The XOR (distinctive OR) operation is a logical operation that takes two operands and returns genuine if and most effective if precisely one of the operands is authentic. In Java, the XOR operation is represented by using the caret symbol (^). While the XOR operation...
4 min read
Merge Sort in Java
Merge sort is similar to the quick sort algorithm as it uses the divide and conquer approach to sort the elements. It is one of the most popular and efficient sorting algorithms. It divides the given list into two equal halves, calls itself for the two...
7 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India