How to Implement Depth-First Search (DFS) Using Recursion

Question

What are the steps to implement Depth-First Search (DFS) using recursion in programming?

Answer

Depth-First Search (DFS) is a fundamental algorithm used for traversing or searching tree and graph data structures. It explores as far as possible along each branch before backing up. DFS can be implemented using recursion, making it an elegant solution for problems with tree-like structures.

def dfs(node, visited):
    if node not in visited:
        print(node)  # Process the node (e.g., print it)
        visited.add(node)  # Mark the node as visited
        for neighbor in node.neighbors:  # Iterate through each neighbor
            dfs(neighbor, visited)  # Recursive call for the neighbor

Solutions

  • Define the base case for the recursive function that processes nodes.
  • Use a helper function that takes a node and a visited set as parameters to track visited nodes.
  • For each unvisited neighbor of the current node, recursively call the DFS function on that neighbor.

Common Mistakes

Mistake: Forgetting to mark nodes as visited, leading to infinite recursion.

Solution: Always add the node to the visited set at the beginning of the function.

Mistake: Not handling edge cases, such as empty graphs or isolated nodes.

Solution: Implement checks for empty inputs and ensure your recursive function can handle them.

Helpers

  • DFS
  • Depth-First Search
  • recursion
  • implement DFS
  • DFS algorithm

Related Questions

⦿Why is ServiceLoader Not Loading Implementations?

Explore why ServiceLoader fails to load implementations and how to resolve common issues in Java applications.

⦿How to Effectively Run Background Processes in Spring Framework

Discover the best practices for executing background processes in Spring Framework with expert insights code examples and troubleshooting tips.

⦿Why Does WeakHashMap Retain Strong References to Values After Garbage Collection?

Explore why WeakHashMap may still hold strong references to values even after garbage collection in Java along with common mistakes and solutions.

⦿How to Delete All Child Entities in Hibernate with a Single Query

Learn how to efficiently delete all child entities in Hibernate using a single query with best practices and expert tips.

⦿How to Disable Automatic Mappings in MapStruct

Learn how to configure MapStruct to prevent automatic mappings with expert tips and code examples for better control over your data mapping.

⦿Understanding Java Type Erasure: Why is the Type Visible in Bytecode?

Explore why Java type erasure allows type visibility in bytecode and understand its implications in generic programming.

⦿How to Send HTML Emails with Plain Text Fallback Using the Gmail API

Learn how to send HTML emails with a plain text fallback using the Gmail API including stepbystep instructions and code examples.

⦿How to Implement a Menu Bar Icon for Dark Mode in Java on macOS

Learn how to create a menu bar icon that supports dark mode in Java applications on macOS with clear instructions and code examples.

⦿How to Resolve the Error: 'The import org.opencv.imgcodecs.Imgcodecs cannot be resolved'

Learn how to fix the error The import org.opencv.imgcodecs.Imgcodecs cannot be resolved with a stepbystep guide and solutions.

⦿How to Fix Issues with Enhanced For Loop When Assigning Values to an Array in Java

Learn how to troubleshoot and resolve issues with the enhanced for loop in Java for array assignments including common mistakes and solutions.

© Copyright 2025 - CodingTechRoom.com