0
我試圖理解這段代碼從檢測週期: http://algs4.cs.princeton.edu/41undirected/Cycle.java.html無向圖中的週期屬性是什麼?
因此,如果一個頂點W是沒有標記或發現,繼續運行DFS。如果它被發現,它不等於你...爲什麼我在構造函數中傳遞-1?
我很困惑其他如果(w!= u)。爲什麼這會導致一個循環?
public Cycle(Graph G) {
if (hasSelfLoop(G)) return;
if (hasParallelEdges(G)) return;
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
for (int v = 0; v < G.V(); v++)
if (!marked[v])
dfs(G, -1, v);
}
private void dfs(Graph G, int u, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
// short circuit if cycle already found
if (cycle != null) return;
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, v, w);
}
// check for cycle (but disregard reverse of edge leading to v)
else if (w != u) {
cycle = new Stack<Integer>();
for (int x = v; x != w; x = edgeTo[x]) {
cycle.push(x);
}
cycle.push(w);
cycle.push(v);
}
}
}
你能再解釋'你'嗎?對我來說不是很清楚。如果W = U讓我們知道我們已經到達了ccycle?我不明白爲什麼它!=。 – runners3431
方法'dfs'被以前訪問過的頂點('u')和下一個要訪問的頂點('v')調用,'v'是'u'的後繼。 –
@SimonS請將解釋添加到您的答案中,不要寫在評論中! –