所以我正在阅读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 …Run Code Online (Sandbox Code Playgroud)