So I'm reading Robert Sedgewick's Algorithms 4th ed. book and the methods for finding a cycle in a directed graph is different than the one for finding a cycle in an undirected graph.
Here is example code to find a Cycle in an undirected graph
public class Cycle {
public boolean[] marked;
public boolean hasCycle;
public Cycle(Graph G) {
marked = new boolean[G.V()]; // G.V() is the number of vertices in the graph G
for (int s = 0; s < G.V(); ++s) {
if (!marked[s])
dfs(G, s, s);
}
}
private void dfs(Graph G, int v, int u) {
marked[v] = true;
for (int w : G.adj(v)) //iterate through vertices adjacent to v
if (!marked[w])
dfs(G, w, v)
else if (w != u) hasCycle= true;
}
public boolean hasCycle() {
return hasCycle;
}
}
However, when trying to find a cycle in a directed graph, Sedgewick uses a boolean array where the ith element of that array is true if the ith vertex has been examined during the current call stack. For every vertex K examined, we check to see if the Kth element of the boolean array is true. If it is, then we have a cycle. My question is, why is it necessary to use that boolean array for a directed graph. Shouldn't the approach I just listed be more memory-efficient? And does this approach only work for undirected graphs? why?