{
  "id": "depth-first-search",
  "title": "Depth-first Search",
  "lang": "en",
  "source_lang": "en",
  "summary": "Depth-first search traverses a graph or tree by exploring each branch as far as possible before backtracking to explore alternatives.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "DFS",
    "depth-first traversal"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/depth-first-search/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/depth-first-search/",
      "json": "https://aiwiki.page/zh/depth-first-search.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Depth-first search (DFS) is an algorithm for exploring a graph or tree by following one branch as far as possible before returning to earlier branching points. Starting at a vertex, it repeatedly visits an unvisited neighbor; when no such neighbor remains, it backtracks. DFS is a fundamental technique in computer science, used both to find reachable vertices and to reveal structural properties such as cycles, connectivity, and dependency order.\n\nUnlike breadth-first search, which explores vertices in layers of increasing distance from a starting point, DFS prioritizes continuing the current path. Its behavior can be implemented through recursion or an explicit stack."
    },
    {
      "heading": "Basic operation",
      "text": "A graph \\(G=(V,E)\\) consists of a set of vertices \\(V\\) and a set of edges \\(E\\). Edges may be directed or undirected. For a directed graph, DFS normally follows edges in their specified direction.\n\nA search from a starting vertex proceeds as follows:\n\n- Mark the vertex as discovered.\n- Examine its neighbors in a specified order.\n- Whenever an undiscovered neighbor is found, explore that neighbor completely before examining the next one.\n- Finish the vertex after all its neighbors have been examined.\n\nMarking vertices prevents repeated exploration when different paths lead to the same vertex or when the graph contains cycles. A search from one starting vertex visits exactly the vertices reachable from it. To traverse an entire graph, the algorithm starts another search at each vertex that remains undiscovered.\n\nEvery discovery of a new vertex establishes a parent–child relationship. These discovery edges form a DFS tree for a single starting point, or a DFS forest when multiple starting points are required. In an undirected graph, each tree in the forest spans one connected component. In a directed graph, the trees do not generally correspond to strongly connected components.\n\nThe traversal order depends on both the order in which starting vertices are selected and the order in which neighbors are examined. DFS therefore does not define a unique ordering for a graph."
    },
    {
      "heading": "Recursive implementation",
      "text": "A common implementation assigns each vertex one of three states:\n\n- White: not yet discovered.\n- Gray: discovered but not yet finished.\n- Black: finished; all outgoing edges have been examined.\n\nThe following pseudocode traverses the entire graph and records discovery and finishing times:\n\nDFS(G):\n    for each vertex u in G:\n        color[u] = WHITE\n        parent[u] = NONE\n\n    time = 0\n\n    procedure VISIT(u):\n        color[u] = GRAY\n        time = time + 1\n        discover[u] = time\n\n        for each v in neighbors(u):\n            if color[v] == WHITE:\n                parent[v] = u\n                VISIT(v)\n\n        color[u] = BLACK\n        time = time + 1\n        finish[u] = time\n\n    for each vertex u in G:\n        if color[u] == WHITE:\n            VISIT(u)\n\nHere, time is shared by all calls to VISIT. The recursive call stack holds the active path from the current DFS root to the vertex being explored. Returning from a call performs the backtracking step.\n\nIf only reachability is needed, a Boolean visited flag is sufficient; the gray–black distinction and timestamps can be omitted. More advanced applications use these additional states to distinguish active vertices from completed ones."
    },
    {
      "heading": "Iterative implementation",
      "text": "DFS can also be implemented without recursive calls. To reproduce the recursive algorithm exactly, including its finishing events, an explicit stack can store frames containing a vertex and its current position in that vertex’s neighbor list:\n\nDiscover start\nPush (start, iterator over neighbors(start))\n\nwhile stack is not empty:\n    (u, iterator) = top frame\n\n    if iterator has another neighbor:\n        v = next neighbor\n        if v is undiscovered:\n            parent[v] = u\n            Discover v\n            Push (v, iterator over neighbors(v))\n    else:\n        Finish u\n        Pop frame\n\nA full-graph traversal repeats this process for every still-undiscovered vertex.\n\nThis frame-based version preserves the recursive algorithm’s behavior when neighbor ordering is the same. A simpler implementation that pushes all neighbors onto a stack can be adequate for reachability, but its discovery order and parent relationships depend on when vertices are marked. In particular, marking every neighbor immediately when it is pushed does not generally reproduce recursive DFS.\n\nThe distinction matters for algorithms that rely on DFS ancestry or finishing order rather than merely on visiting every reachable vertex."
    },
    {
      "heading": "Example and traversal orders",
      "text": "Consider an undirected graph with edges\n\n\\[\\{A,B\\},\\quad \\{A,C\\},\\quad \\{B,D\\},\\quad \\{B,E\\},\\quad \\{C,F\\}.\\]\n\nStarting at \\(A\\) and examining neighbors alphabetically gives the discovery order\n\n\\[A,\\ B,\\ D,\\ E,\\ C,\\ F.\\]\n\nThe search follows \\(A \\rightarrow B \\rightarrow D\\), returns to \\(B\\), explores \\(E\\), returns to \\(A\\), and then explores \\(C\\) and \\(F\\).\n\nThe finishing order is\n\n\\[D,\\ E,\\ B,\\ F,\\ C,\\ A.\\]\n\nThese orders correspond to two common forms of tree traversal:\n\n- Preorder: process a vertex when it is discovered.\n- Postorder: process a vertex when it is finished.\n\nFor a binary tree, inorder traversal is another depth-first convention: traverse the left subtree, process the vertex, and then traverse the right subtree. This convention depends on the distinction between left and right children and has no direct canonical counterpart for general graphs."
    },
    {
      "heading": "Structural properties",
      "text": "Discovery and finishing intervals\n\nFor each vertex \\(u\\), let \\(d(u)\\) be its discovery time and \\(f(u)\\) its finishing time. Then\n\n\\[d(u)<f(u).\\]\n\nFor any two distinct vertices, their discovery–finish intervals are either disjoint or one is contained within the other. In particular, \\(v\\) is a proper descendant of \\(u\\) in the DFS forest exactly when\n\n\\[d(u)<d(v)<f(v)<f(u).\\]\n\nThis nesting property reflects the recursive structure of the search: a vertex finishes only after all of its DFS descendants have finished.\n\nEdge classification\n\nFor directed graphs, edges can be classified relative to the DFS forest:\n\n- Tree edges discover previously unvisited vertices.\n- Back edges lead from a vertex to an ancestor in the DFS tree; self-loops are also treated as back edges.\n- Forward edges lead to proper descendants but are not tree edges.\n- Cross edges connect vertices without an ancestor–descendant relationship in the DFS forest.\n\nWhen an edge is examined, a white destination identifies a tree edge, while a gray destination identifies a back edge. An edge to a black vertex may be a forward or cross edge.\n\nFor an undirected graph, non-tree edges connect ancestors and descendants. Cycle detection must distinguish an edge from the reverse examination of the same tree edge. In a multigraph with parallel edges, this requires tracking edge identity rather than simply ignoring every edge to the parent vertex."
    },
    {
      "heading": "Complexity",
      "text": "For a graph stored with adjacency lists, a complete DFS has time complexity\n\n\\[O(|V|+|E|).\\]\n\nEvery vertex is discovered once, and every adjacency-list entry is examined once. In an undirected graph, an edge commonly appears in two lists, which changes only the constant factor.\n\nWith an adjacency matrix, examining all possible neighbors of every vertex takes\n\n\\[O(|V|^2)\\]\n\ntime, even if relatively few edges exist.\n\nThe standard algorithm uses \\(O(|V|)\\) auxiliary space for vertex states, parent information, and the recursive or explicit stack, excluding storage of the graph itself. Stack depth can reach \\(|V|\\) when the DFS tree is a single long path. Recursive implementations can therefore exhaust a programming environment’s call-stack limit on deep graphs.\n\nOn a tree whose children are generated as needed, the traversal stack may require only \\(O(h)\\) space, where \\(h\\) is the tree’s height. This smaller bound does not include a visited set for arbitrary graphs, storage of all generated children, or retained traversal output."
    },
    {
      "heading": "Applications",
      "text": "Reachability and path finding\n\nDFS determines whether one vertex is reachable from another. Recording parent pointers allows a discovered path to be reconstructed by following the pointers backward.\n\nThe path found is not necessarily shortest. For an unweighted graph, breadth-first search finds paths with the fewest edges. For weighted graphs with nonnegative edge weights, Dijkstra’s algorithm addresses the shortest-path problem.\n\nConnectivity and cycles\n\nRepeated DFS identifies the connected components of an undirected graph.\n\nIn a directed graph, a cycle exists if and only if a complete DFS encounters a back edge. For undirected graphs, an edge to an already discovered vertex can indicate a cycle once the reverse examination of the parent edge is handled correctly.\n\nTopological sorting\n\nA directed acyclic graph admits a topological ordering: an ordering in which the source of every edge precedes its destination.\n\nReversing DFS finishing order produces such an ordering. A detected back edge indicates a directed cycle, in which case no topological ordering exists. This technique is used in dependency analysis and scheduling.\n\nStrongly connected components\n\nA strongly connected component is a maximal set of vertices in a directed graph in which every vertex can reach every other vertex.\n\nSeveral linear-time algorithms use DFS to find these components. Kosaraju’s algorithm combines finishing order with a second traversal of the graph with all edges reversed. Tarjan’s algorithm uses discovery indices, low-link values, and a separate stack to identify components during one DFS-based traversal.\n\nBridges and articulation points\n\nIn undirected graphs, DFS supports linear-time identification of:\n\n- Bridges: edges whose removal increases the number of connected components.\n- Articulation points: vertices whose removal increases the number of connected components.\n\nThese algorithms track whether descendants can reach ancestors through non-tree edges. Their correctness depends on the ancestry structure created by DFS.\n\nBacktracking and state-space search\n\nDFS provides the traversal pattern for backtracking, where partial solutions are extended until they succeed or violate a constraint. Applications include maze solving, puzzle search, and enumerating combinatorial possibilities.\n\nIn this setting, a vertex represents a state or partial solution rather than necessarily an explicitly stored graph vertex. Unlike ordinary graph traversal, some enumeration tasks must revisit a state through different paths, so a global visited set may incorrectly discard valid solutions.\n\nDepth-first exploration also appears in game-tree search and in formal verification, where the explored graph may represent possible system states."
    },
    {
      "heading": "Limitations and variants",
      "text": "On a finite graph, DFS with visited-state tracking terminates and visits every vertex reachable from its starting point. On an infinite or implicitly generated search space, however, unrestricted DFS may follow an infinite branch and never examine another branch containing a solution.\n\nDepth-limited search prevents exploration beyond a chosen depth, but can miss deeper solutions. Iterative deepening depth-first search repeats depth-limited searches with progressively larger limits. Under finite branching and standard tree-search assumptions, it eventually finds a shallowest solution while retaining depth-first-style memory use. The price is repeated exploration of shallower levels.\n\nDFS is not inherently cost-sensitive: neither edge weights nor closeness to a goal determine its default exploration order. Neighbor ordering can greatly affect how soon a solution is found, but ordering alone does not guarantee an optimal solution. Its long dependency chains also make DFS less naturally suited to parallel execution than traversals with large, independently explorable frontiers."
    }
  ],
  "links": [
    "algorithm",
    "graph-theory",
    "tree-data-structure",
    "computer-science",
    "breadth-first-search",
    "recursion",
    "stack-data-type",
    "pseudocode",
    "binary-tree",
    "adjacency-list",
    "time-complexity",
    "adjacency-matrix",
    "space-complexity",
    "dijkstra-algorithm",
    "shortest-path-problem",
    "directed-acyclic-graph",
    "strongly-connected-component",
    "game-tree",
    "formal-verification",
    "parallel-computing"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}