How does the recursive DFS(G, v) work, and what do its labels record?
It marks v as VISITED and then goes through v's incident edges. For each edge still UNEXPLORED it looks at the vertex w on the far side: if w is UNEXPLORED, the edge becomes a DISCOVERY edge and DFS continues recursively from w; if w has been visited already, the edge becomes a BACK edge. When all of v's edges are done, the call returns, and that return is the step back.
void dfs(Graph<V, E> g, Vertex<V> v) {
vertexLabel.put(v, VISITED);
for (Edge<E> e : g.incidentEdges(v)) {
if (edgeLabel.get(e) == UNEXPLORED) {
Vertex<V> w = g.opposite(v, e);
if (vertexLabel.get(w) == UNEXPLORED) {
edgeLabel.put(e, DISCOVERY);
dfs(g, w); // go deeper
} else {
edgeLabel.put(e, BACK); // w was reached before
}
}
}
} // all edges done: back up
The two edge labels sort the edges into two kinds. A discovery edge is the one edge through which a vertex was first reached, so there is exactly one per vertex apart from the start, and together they form the DFS tree. A back edge leads to a vertex that DFS has reached before; in an undirected graph that vertex is always an ancestor of v in the DFS tree, a vertex whose call is still open further down the call stack, so every back edge closes a cycle.
The recursion is what remembers the way back. The call stack holds the chain of calls from the start vertex to v, and when dfs(g, w) returns, the loop over v's edges continues exactly where it stopped. In the complete graph on A, B, C, D, for example, DFS runs straight down A, B, C, D; after the calls for D and C have returned, B's loop still looks at B–D, and A's loop at A–C and A–D, and finds all three labelled BACK already. Here the labels live in two maps, vertexLabel and edgeLabel, filled with UNEXPLORED beforehand; fields in the vertex and edge objects would work the same way.
Go deeper:
USFCA: depth-first search — generates a random graph, runs DFS from the vertex you name and fills a Visited and a Parent table step by step; the graph can also be shown as adjacency list or matrix.