{"id":164,"date":"2026-11-13T12:33:15","date_gmt":"2026-11-13T04:33:15","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-depth-first-search-records-discovery-and-finish\/"},"modified":"2026-11-13T21:51:38","modified_gmt":"2026-11-13T13:51:38","slug":"how-depth-first-search-records-discovery-and-finish","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-depth-first-search-records-discovery-and-finish\/","title":{"rendered":"How depth-first search records discovery and finish"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Depth-first search<\/strong> follows an edge as far as it can, then backtracks, using a stack or the call stack. Each vertex receives a <strong>discovery time<\/strong> and a <strong>finish time<\/strong>. Those times classify every edge as tree, back, forward, or cross, and the finish order is the input to topological sort and to Kosaraju&#8217;s strongly connected components. The scan is <strong>\u0398(V+E)<\/strong>. It does not compute shortest paths.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Some graph facts are about ancestry in a search forest, not about distance. A back edge points at an ancestor and, in a directed graph, closes a cycle. A finish time records the moment the entire descendant subtree is done. Algorithms that need those facts want a traversal that stays with one child until that child is exhausted.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The stack produces that stay. A queue would finish a level before any grandchild, and the finish times would mean something else. The price is that the path by which a vertex was discovered can be arbitrarily longer than a shortest path.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">One adjacency-list search runs in \u0398(V+E) and uses \u0398(V) stack space in the worst case, a single path through every vertex. Discovery and finish times are integers from 1 to 2V. The parenthesis theorem says the interval [discovery, finish] of a vertex either contains the interval of another vertex or is disjoint from it. Containment means ancestry in the depth-first forest.<\/p>\n\n\n<p class=\"wp-block-paragraph\">In a directed graph an edge u\u2192v is a tree edge if it discovers v, a back edge if v is an ancestor of u, a forward edge if v is a descendant and the edge is not the tree edge, and a cross edge otherwise. In an undirected graph every non-tree edge is a back edge to an ancestor. A back edge in a directed graph witnesses a cycle. An undirected cycle is a back edge to an ancestor that is not the parent.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Mark every vertex undiscovered. The clock starts at zero.<\/li>\n<li>For each vertex that is still undiscovered, begin a search there. This outer loop is what finds every component or every source-side piece of a directed graph.<\/li>\n<li>On entering u, mark it discovered, stamp the discovery time, and scan its adjacency list.<\/li>\n<li>Recur, or push, on each undiscovered neighbor. After the list is exhausted, stamp the finish time.<\/li>\n<li>Classify edges from the colors at the moment they are examined: undiscovered means tree, discovered-and-unfinished means back, finished means forward or cross depending on the timestamps.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The timestamps are a traversal record. They are not distances. Using the tree path as a route is safe only when any path will do. Shortest unweighted paths belong to breadth-first search. The same timestamps, read in reverse finish order, are a topological order when the directed graph has no back edge.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a depth-first tree is read as a shortest-path tree<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Report the tree path as a minimum-hop path<\/td>\n<td>The search may dive down a long branch before a one-edge path is ever looked at. Hop count belongs to a queue.<\/td>\n<\/tr>\n<tr>\n<td>Ignore the outer loop over undiscovered vertices<\/td>\n<td>A directed graph, and an undirected graph with several components, is not always reachable from vertex 0. Those vertices never receive times.<\/td>\n<\/tr>\n<tr>\n<td>Detect an undirected cycle from every back edge, including the edge to the parent<\/td>\n<td>The parent edge is how the search arrived. A cycle is a back edge to some other ancestor.<\/td>\n<\/tr>\n<tr>\n<td>Recur on a graph with a long path and no explicit stack<\/td>\n<td>The call stack is \u0398(V) and can overflow a fixed language stack. An explicit stack has the same asymptotics and a controllable memory limit.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Minimum hops belong to breadth-first search. A directed acyclic order belongs to topological sort, which is this finish order with the cycle test made explicit. Strongly connected components via the transpose belong to Kosaraju.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script depth-first search from vertex 0 and record discovery time, then finish time. Edges are 0\u21921, 0\u21922, 1\u21923, 2\u21923. Both print discovery <code>0 1 5 2<\/code> and finish <code>7 4 6 3<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">adj=(&quot;1 2&quot; &quot;3&quot; &quot;3&quot; &quot;&quot;)\ndisc=(-1 -1 -1 -1)\nfin=(-1 -1 -1 -1)\nclk=0\ndfs() {\n  local u=$1 v\n  disc[u]=$clk\n  clk=$((clk+1))\n  for v in ${adj[u]}; do\n    if (( disc[v] &lt; 0 )); then dfs &quot;$v&quot;; fi\n  done\n  fin[u]=$clk\n  clk=$((clk+1))\n}\ndfs 0\necho &quot;${disc[*]}&quot;\necho &quot;${fin[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">adj = [[1, 2], [3], [3], []]\ndisc = [-1] * 4\nfin = [-1] * 4\nclock = 0\n\ndef dfs(u):\n    global clock\n    disc[u] = clock\n    clock += 1\n    for v in adj[u]:\n        if disc[v] &lt; 0:\n            dfs(v)\n    fin[u] = clock\n    clock += 1\n\ndfs(0)\nassert disc == [0, 1, 5, 2] and fin == [7, 4, 6, 3]\nprint(*disc)\nprint(*fin)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Depth-first search is the walk a compiler makes over a control-flow graph, the cycle check in a dependency graph, and the mark phase of a tracing garbage collector. Topological order is one of its outputs on a DAG. Breadth-first search is the walk that measures hops.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop depth-first search when the deliverable is a shortest path. Keep it when the deliverable is a finish order, a cycle witness via a back edge, a topological order of a DAG, or the input pass of an algorithm that already says it needs discovery and finish times.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for depth-first search returns the discovery and finish times and the edge classes those times define. <strong>Depth-first search stamps discovery and finish times in linear time, and those intervals classify edges and expose cycles, without measuring distance.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Depth-first search follows an edge as far as it can, then backtracks, using a stack or the call stack. Each vertex receives a discovery time and a finish time. Those times classify every edge as tree, back, forward, or cross, and the finish order is the input&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,32],"tags":[],"class_list":["post-164","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-graphs"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/164","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=164"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/164\/revisions"}],"predecessor-version":[{"id":563,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/164\/revisions\/563"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=164"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=164"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=164"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}