Most of the time we need to understand someone else' code for example I am studying Graph Algorithms from Sedgewick's online resources, the particular code example is taken from cycle detection algorithm here:
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);
}
}
}
Although I know the basic gist of the algorithm(finding the back edge) and I can tell from looking at the code that its trying to store the generated cycle as well but I am not able to trace how would the algorithm would execute and why the author has takes one extra parameter in the dfs
code. Generally how should I proceed to understand such recursive algorithms?
dfs(g, s)
whereg
is the graph instance ands
is the start vertex. But now I see one extra vertex in the parameter of dfs.