CodexBloom - Programming Q&A Platform

implementing Implementing a Depth-First Search in Java for a Graph with Cycles

πŸ‘€ Views: 62 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
java algorithms graph-theory Java

I'm stuck trying to I'm testing a new approach and I tried several approaches but none seem to work. I'm following best practices but I've been banging my head against this for hours... I'm trying to implement a depth-first search (DFS) algorithm in Java for a directed graph, but I'm running into issues when handling graphs with cycles. My current implementation sometimes leads to infinite loops when traversing cycles, and I'm not sure how to properly track visited nodes. Here’s the code I’ve written so far: ```java import java.util.*; class Graph { private final Map<Integer, List<Integer>> adjacencyList = new HashMap<>(); public void addEdge(int source, int destination) { adjacencyList.computeIfAbsent(source, k -> new ArrayList<>()).add(destination); } public void depthFirstSearch(int start) { Set<Integer> visited = new HashSet<>(); dfsUtil(start, visited); } private void dfsUtil(int node, Set<Integer> visited) { if (visited.contains(node)) { System.out.println("Already visited: " + node); return; } visited.add(node); System.out.println("Visiting: " + node); for (int neighbor : adjacencyList.getOrDefault(node, new ArrayList<>())) { dfsUtil(neighbor, visited); } } } public class Main { public static void main(String[] args) { Graph graph = new Graph(); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(3, 1); // Cycle here graph.depthFirstSearch(1); } } ``` When I run this code, I get the output: ``` Visiting: 1 Visiting: 2 Visiting: 3 Already visited: 1 ``` It seems to print "Already visited: 1" but then doesn't stop, essentially getting exploring in a loop. I added checks for visited nodes, so I'm confused why it continues to iterate through the cycle. Could anyone suggest what I might be missing or how to effectively modify my DFS implementation to handle cycles better? I'm using Java 11 and trying to follow best practices for graph traversal. Thanks in advance! Any help would be greatly appreciated! My development environment is Windows. Any ideas what could be causing this? I recently upgraded to Java LTS. How would you solve this? Any pointers in the right direction? This is happening in both development and production on Windows 10. Is this even possible?