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);
}
}