0

I am trying to write an algorithm that determines whether a graph is strongly connected or not. I think my code is almost correct, although I keep getting StackOverFlowError. I personally think because there's a cycle in the graph I'm testing my algorithm with, my code doesn't understand that and comes in a loop. But I'm using an array to see if a node was already visited! So that should not happen! Please help me understand what's wrong with my code. Anyways this is my code:

 static void dfs(int src,boolean[] visited,Stack<Integer> stack){
        visited[src]=true;
        for(Integer i:adj[src]){
            if(!visited[i]){
                dfs(i,visited,stack);
            }
        }
        stack.push(src);
    }

This is how I called my DFS function from main:

Stack<Integer> stack=new Stack<Integer>();
    boolean[] visited=new boolean[n+1];
    for(int i=1;i<=n;i++){
        if(!visited[i]){
            g.dfs(i,visited,stack);
        }
    }
  • maybe this will help you: https://stackoverflow.com/questions/34553782/how-to-implement-dfs-using-recursion?rq=1 – yassadi May 12 '18 at 05:06
  • You are updating `visited` using `src` which is I guess the node number ? Where is `g` defined ? `if(!visited[i]){ g.dfs(i,visited,stack);` is also not clear to me : if you want to start dfs from every possible node, ignore `visited`. Please post [mcve] so we do not need to guess. – c0der May 12 '18 at 05:32

1 Answers1

0

There are two possible explanations:

  1. There is a loop and your loop detection code isn't working.
  2. The graph is too deep; i.e. your code would work if the stack was larger.

Looking at your code, I think that the second explanation is the correct one.

Example: suppose that your graph is actually a chain of N nodes in a line. To reach the last node in the list you need to make recursive calls N deep. For large enough N, that will cause a stack overflow.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Contraints for the question are: 1 ≤ N ≤ 10^5 I think such stack space is not large enough to cause stackoverflow error. Is there any solution to overcome this situation? – Shreya Jain May 12 '18 at 05:27
  • @ShreyaJain you can apply a non-recursive dfs, or run the recursion in intervals. See an example [here](https://stackoverflow.com/a/46022542/3992939) – c0der May 12 '18 at 05:35
  • *"I think such stack space is not large enough to cause stackoverflow error"* I don't. *"Is there any solution to overcome this situation?"* Use an explicit stack data structure rather than recursion. – Stephen C May 12 '18 at 05:36