我正在阅读Robert Sedgewick的《算法》第4版,其中寻找有向图中的环的方法与寻找无向图中的环的方法不同。
下面是在无向图中查找环的示例代码:
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;
}
}
不过,在尝试在有向图中找到一个环时,Sedgewick使用了一个布尔数组,其中该数组的第i个元素为真,如果在当前调用堆栈期间检查了第i个顶点。对于每个检查的顶点K,我们检查布尔数组的第K个元素是否为true。如果是,则表示存在一个环。我的问题是,在有向图中使用那个布尔数组是为什么必要的?我列出的方法难道不会更节省内存吗?这种方法只适用于无向图吗?为什么?