I am working on finding cycles in directed graph using recursive backtracking. There is a suggested pseudocode for this here, which is here:
dfs(adj,node,vis
For (1 2),(2 3),(3 1)
, you're calling:
dfs(vertex1, vertex1, count)
, which gives you the cycle 1 -> 2 -> 3 -> 1
.dfs(vertex2, vertex2, count)
, which gives you the cycle 2 -> 3 -> 1 -> 2
.dfs(vertex3, vertex3, count)
, which gives you the cycle 3 -> 1 -> 2 -> 3
.So you're counting the same cycle multiple times.
The simplest fix I can think of is simply setting the visited flag after the dfs
call.
public int allCyclesDirectedmain(){
clearAll();
int[] count = new int[1];
for (Vertex v: vertexMap.values()){
dfs(v,v,count);
v.setVisited(true); // <---
}
return count[0];
}