Search code examples
algorithmrecursiondepth-first-search

Is there a good way to exit a DFS procedure?


I've learned that a recursive depth-first search procedure searches a whole tree by its depth, tracing through all possible choices.

enter image description here

However, I want to modify the function such that I can call a "total exit" in the middle, which will completely stop the recursion. Is there an efficient way to do this?


Solution

  • There are 3 ways to do this.

    1. Return a value saying you are done, and check for it after every call.
    2. Throw an exception and catch it at the top level.
    3. Switch from recursion to a stack and then break the loop.

    The third is the most efficient but takes the most work. The first is the clearest. The second is simple and works..but tends to make code more complicated and is inefficient in many languages.