JAVA PROGRAM • LEVEL 17 — DATA STRUCTURES & ALGORITHMS IN JAVA
Traverse a Graph with DFS in Java
Learn traverse a graph with dfs in java with a complete, compiler-ready Java 17 example.
PROBLEM UNDERSTANDING
Input and expected output
No input required
0 1 3 2
COMPLETE JAVA 17 PROGRAM
Complete Java 17 implementation
import java.util.*;class Main{static void dfs(int u,List<List<Integer>> g,boolean[] seen){seen[u]=true;System.out.print(u+" ");for(int v:g.get(u))if(!seen[v])dfs(v,g,seen);}public static void main(String[] args){List<List<Integer>> g=List.of(List.of(1,2),List.of(0,3),List.of(0,3),List.of(1,2));dfs(0,g,new boolean[4]);}}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 3 2
PROGRAM EXPLANATION
Algorithm and explanation
- Initialize the deterministic sample values used for traverse a graph with dfs in java.
- Apply Graph and Depth-first search in the order shown by the program.
- Print the final result and compare it with the documented sample output.
This Java 17 example demonstrates Graph and Depth-first search through a complete, executable program. The values are intentionally small so students can trace each statement, verify the output, and then modify the example safely in the online compiler.
EFFICIENCY
Time and space complexity
O(V + E)
O(V)
DEBUGGING CHECKLIST
Common mistakes
Keep the class name Main and the entry method signature public static void main(String[] args) when using the online compiler.
Check the loop boundary and update expression carefully to avoid skipping the final value or creating an infinite loop.
Java is case-sensitive, and every statement that requires a semicolon must end with one.
