Fact-checked by Grok 2 weeks ago

Depth-first search

Depth-first search (DFS) is an for traversing or searching or structures by exploring as far as possible along each branch before . The begins at an arbitrary source and recursively visits adjacent unvisited vertices, marking them as visited to avoid cycles, until no further exploration is possible from the current path; it then backtracks to explore alternative branches. This process continues until all reachable vertices have been visited, potentially forming a depth-first if the is disconnected. Although the underlying strategy traces back to 19th-century maze-solving techniques devised by French mathematician Charles Pierre Trémaux for undirected s, the formalization of DFS in emerged in the early as a versatile tool for analysis. Robert Tarjan's 1972 paper advanced its application by demonstrating linear-time algorithms for finding strongly connected components in directed graphs and biconnected components in undirected graphs using DFS. DFS can be implemented iteratively with an explicit or recursively, with the latter leveraging the call for efficiency in practice. The algorithm runs in linear time, specifically O(V + E), where V is the number of vertices and E is the number of edges, as it processes each vertex and edge a constant number of times. Key properties include discovery and finishing times for vertices, which enable edge classification into tree, back, forward, and cross edges, providing insights into graph structure. DFS underpins numerous applications, such as topological sorting in directed acyclic graphs (DAGs), cycle detection, finding connected components, and solving puzzles like mazes.

Fundamentals

Definition

Depth-first search (DFS) is a that explores as far as possible along each branch or path from a starting before to explore alternative paths. This approach systematically delves into the graph's structure by prioritizing depth over breadth, making it a fundamental method for navigating connected components in graph data structures. DFS operates on both undirected and directed graphs, which must be represented in a form that allows efficient access to neighboring vertices, such as adjacency lists or adjacency matrices. Adjacency lists, consisting of arrays or lists where each index corresponds to a vertex and holds its adjacent vertices, are particularly efficient for sparse graphs, while matrices provide constant-time neighbor queries suitable for dense graphs. The algorithm's motivation stems from simulating manual exploration of a or , where one follows a path to its end before retreating, which proves effective for tasks like determining between () and verifying graph connectivity. In its basic execution, DFS begins by marking the starting as visited and then recursively processes each unvisited in turn; once all neighbors of a have been explored, the algorithm backtracks to the previous to continue from there. This process can equivalently be viewed as using an explicit to manage the of to explore, though recursive implementations are more common for simplicity.

Historical Development

The concept of depth-first search traces its roots to the , where French mathematician Charles Pierre Trémaux described a systematic traversal method for solving mazes, marking paths to avoid cycles and when dead ends were reached. This approach, known as Trémaux's , represented an early form of recursive exploration in graph-like structures, though it predated modern computational . In the mid-20th century, as emerged, depth-first search evolved through techniques applied to combinatorial problems. A key early formalization appeared in 1965, when and Leonard D. Baumert introduced "backtrack programming" as an efficient method for exhaustive search in discrete problems, such as generating combinatorial configurations, using recursive depth exploration to prune invalid paths. This work laid groundwork for algorithmic implementations of depth-first traversal in computational settings. The modern formulation of depth-first search in graph algorithms was pioneered in the late 1960s by John Hopcroft and during their collaboration at . They recognized its potential for efficient graph processing, leading to technical reports in 1971 that utilized DFS for tasks like and connectivity analysis. Tarjan's seminal 1972 paper further demonstrated how DFS enables linear-time algorithms for problems such as finding strongly connected components and biconnected components, establishing it as a cornerstone of . By the 1970s, depth-first search had become integral to education and literature. Donald E. Knuth incorporated it into his influential series , beginning with discussions in Volume 1 (1968) on tree traversals and expanding in later volumes on graph algorithms, highlighting its utility in systematic exploration. This integration, alongside Hopcroft and Tarjan's contributions, solidified DFS's role in advancing efficient graph manipulation techniques.

Algorithm Mechanics

Recursive Formulation

The recursive formulation of depth-first search (DFS) implements the traversal using a recursive procedure that explores as far as possible along each path before , leveraging the system's to manage the exploration depth. The begins by invoking the DFS function on an initial , which marks the node as visited and then recursively calls itself on each unvisited of that node, prioritizing depth over breadth. This recursive expansion continues until a leaf or a node with no unvisited neighbors is reached, at which point the function returns to the previous caller, simulating to explore alternative paths. While the recursive structure applies to both trees and graphs, the handling differs due to the presence of cycles in general graphs. In trees, which lack cycles, recursion can proceed without a global visited set by simply avoiding recursion on the , ensuring termination without loops. However, for graphs, a visited set or array is essential to track discovered s and prevent infinite on cycles, as revisiting a could otherwise lead to endless calls along looped paths. This visited mechanism ensures each is explored exactly once, maintaining the algorithm's efficiency and correctness across connected components. Backtracking in the recursive formulation occurs naturally when the recursive calls exhaust all unvisited neighbors of a , causing the to return control to the prior invocation in the . This return propagates upward, allowing the algorithm to resume exploration from unexplored branches at higher levels, ultimately covering the entire reachable from the starting . The process repeats for any unvisited nodes in the to ensure . The core structure of the recursive DFS can be expressed in high-level as follows:
DFS(node):
    mark node as visited
    for each neighbor in adjacent[node]:
        if neighbor not visited:
            DFS(neighbor)
This formulation highlights the recursive call on unvisited neighbors, with the visited marking preventing redundant exploration in graphs.

Iterative Formulation

The iterative formulation of depth-first search (DFS) employs an explicit to simulate the call stack used in the recursive version, enabling traversal without relying on language-provided . This approach begins by initializing a with the starting and a visited set to track processed nodes, then repeatedly pops a vertex from the , marks it as visited if not already done, and pushes its unvisited neighbors onto the to explore deeper paths first due to the last-in, first-out (LIFO) nature of the . To ensure the visitation order matches the standard recursive DFS, where neighbors are explored from left to right in the , the unvisited neighbors are typically pushed onto the in reverse order, so the first neighbor is popped and processed last among them. Like the recursive formulation, the iterative version requires a to detect and avoid cycles by preventing re-exploration of already marked vertices. This method offers advantages over recursion, particularly in graphs with deep structures where recursive calls might exceed the system's stack depth limit, causing overflow; the explicit stack allows for larger traversals limited only by available memory. It also provides finer control over the traversal order through direct stack manipulation. The following pseudocode outlines the core iterative DFS procedure for a graph G starting from vertex s:
procedure IterativeDFS(G, s)
    stack ← empty stack
    visited ← empty set
    push s onto stack
    while stack is not empty do
        u ← pop from stack
        if u not in visited then
            add u to visited
            // Process u (e.g., record discovery)
            for each neighbor v of u in reverse adjacency order do
                if v not in visited then
                    push v onto stack
                end if
        end if
    end while
end procedure

Properties and Outputs

Key Properties

Depth-first search (DFS) exhibits a fundamental property of prioritizing deep exploration along each path before , which distinguishes it from breadth-first approaches. This depth-first behavior leads to the construction of a in the , where the predecessor induced by DFS consists of rooted at the starting vertices, along with back edges that connect vertices within the same tree. In directed graphs, edges are classified as tree edges (forming the forest paths from a vertex to its descendants), back edges (pointing to in the ), forward edges (from an ancestor to a non-child descendant in the tree), or edges (connecting vertices in different trees or non-ancestor-descendant pairs in the same traversal). In undirected graphs, non-tree edges are back edges to ancestors. This ensures that the traversal explores the in a recursive, stack-like manner without revisiting fully processed subtrees. A key mechanism in DFS involves assigning discovery and finishing times to vertices, which capture the temporal structure of the traversal. The discovery time d for a vertex u is recorded when u is first encountered and marked as visited (typically colored gray), while the finishing time f is set after all adjacent vertices have been explored and u is marked as finished (black). These timestamps satisfy the parenthesis theorem: for any two vertices u and v, the intervals [d, f] and [d, f] are either disjoint or one is nested within the other, reflecting ancestor-descendant relationships in the DFS tree. This property enables efficient analysis of graph structure, such as identifying cycles via back edges where d < d < f < f for an edge (u, v). In undirected graphs, DFS partitions the vertices into connected components through its forest structure, where each tree in the forest corresponds to a distinct component, and all back edges lie within the same component. The roots of these trees are the vertices from which new DFS calls are initiated when unvisited portions of the graph are encountered, effectively delineating the graph's connectivity without requiring prior knowledge of component boundaries. Unlike breadth-first search, which computes shortest paths in terms of edge count from a source, DFS provides no such guarantees and instead focuses on determining reachability and topological properties. Paths found by DFS may traverse unnecessary detours, making it unsuitable for distance-based queries but ideal for exhaustive exploration of reachable subgraphs.

Vertex Orderings

In depth-first search (DFS), vertices are processed in specific sequences based on the timing of their discovery and completion during the traversal. These orderings arise naturally from the recursive structure of the algorithm, where a vertex is discovered upon initial visit, and its exploration proceeds by recursively visiting adjacent unvisited vertices before backtracking and marking the vertex as finished. This backtracking mechanism ensures that subtrees (or subgraphs) are fully explored before returning to the parent vertex. The sequence records vertices in the order of their discovery, assigning each a unique discovery time (or preorder number) as it is first encountered. For instance, in a with vertices A, B, and C connected linearly as A → B → C, starting DFS from A yields the A, B, C, reflecting the progression deep into the structure before any . These discovery times facilitate analysis of traversal paths and are foundational for classifying edges in the DFS . The post-order sequence captures vertices in the order they finish, meaning after all outgoing edges and descendant vertices have been fully explored. In the same linear graph example, the post-order is C, B, A, as C finishes first (with no descendants), followed by B and then A upon . Post-order is particularly valuable in directed acyclic graphs (DAGs), where the reverse of this sequence produces a valid topological ordering, ensuring that for every directed edge u → v, u appears before v in the ordering. Reverse post-order, obtained by reversing the post-order sequence, directly yields the topological sort in DAGs and supports applications such as task scheduling, where dependencies must be respected by processing sources before sinks. In the linear example, reverse post-order is A, B, C, aligning with the natural dependency flow from A to C. This ordering emerges from the recursive completion times, prioritizing vertices whose subgraphs are resolved last in the forward traversal but first in the reversed view.

Implementations and Examples

Pseudocode

The pseudocode for depth-first search (DFS) is typically presented in both recursive and iterative forms, assuming the graph is represented as an where the graph G = (V, E) has set V and edge set E, with a designated starting s \in V. These formulations handle both directed and undirected graphs identically, as the adjacency list encodes the edge directions (for directed graphs) or bidirectional connections (for undirected graphs); the algorithm traverses edges as specified in the list without modification. The recursive version uses the call stack to explore as far as possible along each branch before , marking to avoid cycles. A standard implementation employs a to track states: (undiscovered), gray (discovered but under exploration), and black (fully explored).
DFS(G)
1  for each [vertex](/page/Vertex) u ∈ V[G]
2      color[u] ← WHITE
3      π[u] ← NIL
4  time ← 0
5  for each [vertex](/page/Vertex) u ∈ V[G]
6      if color[u] = WHITE
7          DFS-VISIT(u)

DFS-VISIT(u)
8  color[u] ← GRAY
9  time ← time + 1
10 d[u] ← time
11 for each v ∈ Adj[u]
12     if color[v] = WHITE
13         π[v] ← u
14         DFS-VISIT(v)
15 color[u] ← BLACK
16 time ← time + 1
17 f[u] ← time
This pseudocode initializes all vertices as white, then iteratively calls DFS-VISIT on unvisited starting points to form a depth-first forest; discovery time d and finishing time f are optional for tracking order. The iterative version simulates using an explicit , pushing vertices to explore and marking them upon processing to prevent revisits, which avoids recursion depth limits at the cost of explicit management.
DFS-ITER(G, s)
1  create a [stack](/page/Stack) S
2  visited[v] ← false for all v ∈ V[G]
3  S.push(s)
4  while S ≠ ∅
5      u ← S.pop()
6      if not visited[u]
7          visit(u)  // process u, e.g., record discovery
8          visited[u] ← true
9          for each v ∈ Adj[u]  // optionally reverse order to match [recursion](/page/Recursion)
10             if not visited[v]
11                 S.push(v)
Here, the operates in last-in-first-out to prioritize depth, and vertices are marked visited only when popped and processed, ensuring each is handled once; for exact replication of recursive discovery , neighbors may be pushed in reverse adjacency . suits deep graphs with sufficient stack space, while is preferable for very deep graphs to mitigate risks.

Illustrative Examples

To illustrate depth-first search (DFS) on an undirected , consider a simple 4-vertex with vertices labeled 1, 2, 3, and 4, connected by 1-2, 2-3, 3-4, and 4-1. Starting DFS from vertex 1, the algorithm first visits 1, then recursively explores neighbor 2 (assuming adjacency lists order neighbors sequentially), followed by 3, and then 4. Upon reaching 4, the to 1 is encountered, but 1 is already visited, classifying it as a back edge. The visited order ( sequence) is thus 1, 2, 3, 4, and the consists of the tree edges 1-2, 2-3, and 3-4, forming a path that covers all vertices without the back edge. A step-by-step trace of this traversal, with timestamps indicating visit order, proceeds as follows: at step 1, visit 1 (mark as visited); at step 2, from 1 recurse to 2 (visit 2); at step 3, from 2 to 3 (visit 3); at step 4, from 3 to 4 (visit 4); at step 5, from 4 attempt 1 but skip as visited, then backtrack through 4, 3, 2, and finally 1. This highlights how DFS builds a depth-oriented while identifying via back to ancestors. For a example demonstrating back and , examine a small with vertices v1, v2, v3, and directed v1 → v2, v2 → v3, v3 → v1 (forming a ), plus an additional v1 → v4 where v4 has no outgoing . Starting from v1, DFS visits v1, then recurses to v2 (visit v2), then to v3 (visit v3), and from v3 encounters the edge to v1, which is already visited but not yet finished (in the ), confirming a back and detecting the v1-v2-v3-v1. The algorithm then backtracks to v1 and explores v4 (visit v4), completing the traversal. The visited order is v1, v2, v3, v4, with the back v3 → v1 triggering during the recursive calls. Step-by-step with timestamps: at step 1, mark v1 as visiting and recurse to v2; at step 2, mark v2 visiting and recurse to v3; at step 3, mark v3 visiting, find edge to v1 (visiting, not finished) → detect ; backtrack to v3 (finish), v2 (finish), then from v1 to v4 at step 4 (mark v4 visiting, no children, finish v4); finally finish v1. This process uses three colors (unvisited, visiting, visited) to distinguish back edges from tree edges, enabling efficient in directed graphs. In the context of trees, which are acyclic undirected graphs, DFS manifests as standard tree traversals such as and post-order. Consider the following :
       38
     /    \
    5      45
  /  \       \
 1    9       47
     / \      /
    8   15   46
       /
      13
A DFS traversal (visit , then left subtree, then right subtree) yields the sequence 38, 5, 1, 9, 8, 15, 13, 45, 47, 46, starting at the and descending leftward before rightward branches. In contrast, a post-order DFS (left subtree, right subtree, then ) produces 1, 8, 13, 15, 9, 5, 46, 47, 45, 38, processing subtrees fully before the root. These orders demonstrate how DFS explores depth-first, with suitable for copying tree structures and post-order for computations like expression evaluation. Step-by-step for pre-order: at step 1, visit 38 (pre); step 2, recurse left to 5 (pre), step 3 to 1 (pre, leaf); back to 5, step 4 to 9 (pre), step 5 to 8 (pre, leaf), step 6 to 15 (pre), step 7 to 13 (pre, leaf); back through subtrees to 5, then right from 38 to 45 (pre), step 8 to 47 (pre), step 9 to 46 (pre, leaf). This recursive depth ensures complete subtree exploration before backtracking.

Applications and Analysis

Practical Applications

Depth-first search (DFS) is commonly applied to determine connectivity by identifying connected components in undirected graphs, where each component represents a maximal set of vertices reachable from one another via undirected edges. This technique partitions the into disjoint subgraphs, facilitating analysis in network structures such as social networks or circuit designs. Additionally, DFS detects bridges—critical edges whose removal increases the number of connected components—by tracking discovery times and low values during traversal, aiding in for robust system design. In directed graphs, DFS enables by identifying back edges that connect to ancestors in the DFS tree, which is essential for resolving dependencies in systems or operating system to prevent deadlocks. For instance, in package management, detecting cycles ensures acyclic dependency graphs, allowing safe installation orders. DFS supports topological sorting in directed acyclic graphs (DAGs) by ordering vertices based on their finishing times from the traversal, ensuring that for every directed edge from vertex u to v, u precedes v in the ordering. This application is pivotal in scheduling tasks with precedence constraints, such as job sequencing in or course prerequisite planning in educational systems. For pathfinding, DFS explores paths deeply from a source until a target is reached or all branches are exhausted, making it suitable for detecting any path or simple cycles in networks like communication systems or puzzle games. In game development, it efficiently navigates complex maps to find routes between points, though it may not guarantee the shortest path. Beyond core graph problems, DFS solves mazes by treating as a and traversing paths recursively until the exit is found, a originating from early algorithmic designs for puzzle . In expression , recursive DFS-like traversals build parse for arithmetic or logical expressions, enabling syntactic analysis in programming languages. Compiler optimizations leverage DFS for analysis, such as numbering basic blocks in postorder to propagate dataflow information efficiently during or loop invariant motion.

Complexity Analysis

The of depth-first search (DFS) is O(V + E), where V is the number of and E is the number of in the . This bound arises because the algorithm visits each exactly once and examines each a constant number of times—specifically, once from each endpoint in undirected graphs or once in directed graphs. To sketch the proof, consider the DFS procedure: initialization and the main loop over each take O(V) time, while the recursive calls in DFS-VISIT collectively spend O(E) time traversing , as the sum of the degrees (or out-degrees) equals E. Thus, the total time is O(V + E), assuming an representation. The space complexity of DFS is O(V), accounting for the visited set, auxiliary arrays (such as for discovery times or predecessors), and the or explicit in iterative implementations. In the recursive formulation, the stack depth can reach O(V) in the worst case, such as in a linear forming a deep path, potentially leading to for very large graphs. The iterative version uses an explicit of size up to O(V), avoiding overhead but maintaining the same asymptotic bound. Influencing factors include the graph's representation: with an , the time remains O(V + E), efficient for sparse graphs where E \ll V^2. However, using an increases the time to O(V^2), as checking neighbors for each of the V vertices requires scanning O(V) potential edges per vertex, regardless of actual edges present; this is suitable for dense graphs where E \approx V^2. Space for an is O(V^2), contrasting with O(V + E) for lists.

Extensions

Variations

One prominent variation of depth-first search (DFS) employs a color-marking scheme to track states during traversal, particularly for detecting s in directed graphs. are assigned one of three colors: for unvisited nodes, gray for nodes currently being explored (indicating an active path), and black for nodes whose exploration is complete. A is detected if, during traversal from a gray , an adjacent is found to be gray, signifying a back to an in the current . This approach ensures that DFS can identify in O(V + E) time, where V is the number of and E is the number of , by avoiding redundant traversals and efficiently marking completion. Bidirectional DFS extends the standard by performing two simultaneous searches: one forward from the starting and one backward from the , both using DFS until their frontiers meet. This variation is particularly useful in problems on large graphs, where it can reduce the search space by meeting in the middle, potentially achieving exponential speedup in time complexity compared to unidirectional DFS in balanced trees or graphs with short . The is verified by checking for a common , and the is reconstructed by combining the two search trees. Seminal work on , including DFS variants, demonstrated its efficacy for heuristic path problems, though care must be taken to handle asymmetric graphs where forward and backward searches may differ. Parallel DFS adaptations distribute the traversal across multiple processors to handle massive graphs in high-performance computing environments, addressing the sequential nature of standard DFS by partitioning the and synchronizing explorations. In distributed settings, vertices are assigned to processors, and DFS proceeds by exploring subgraphs while communicating boundary edges via , often using work-stealing to balance load. For directed acyclic graphs, optimized parallel versions achieve near-linear on GPUs by independent paths concurrently, with implementations scaling to billions of edges. Early analyses showed that dynamic load balancing is crucial, as uneven subtree sizes can lead to idle time, but techniques like queues for unexplored subgraphs mitigate this in practice. Breadth-first search (BFS) is a fundamental graph traversal algorithm that explores vertices level by level, processing all neighbors of a vertex before advancing to the next depth, typically implemented using a queue. In contrast, depth-first search (DFS) delves as deeply as possible along each branch using a stack or recursion before backtracking, prioritizing depth over breadth. This level-order strategy in BFS ensures it finds the shortest path in terms of the number of edges in unweighted, undirected graphs, making it ideal for distance computations, whereas DFS excels in reachability checks and cycle detection without guaranteeing minimal paths. Iterative deepening depth-first search (IDDFS) addresses limitations of pure DFS by repeatedly applying depth-limited DFS with incrementally increasing depth bounds until the goal is found, effectively mimicking BFS's completeness while retaining DFS's linear . Developed by Korf in , IDDFS achieves asymptotic optimality in time, space, and node expansions for exponential tree searches, combining the low of DFS with BFS-like guarantees for optimal solutions in uniform-cost domains. Backtracking employs DFS as its core mechanism to explore solution spaces for combinatorial and problems, incrementally building candidate solutions and pruning invalid partial paths by "backtracking" to previous choices when a dead end is reached. This approach, formalized by Golomb and Baumert in 1965 for enumerative problems like the , leverages DFS's recursive structure to efficiently generate and test permutations or assignments, often enhanced with heuristics like constraint propagation to reduce search time. The complements DFS in handling queries by maintaining dynamic partitions of elements through operations that merge sets and find operations that identify set representatives, achieving amortized nearly constant with by and . Introduced in foundational work by McIlroy and Morris in the and analyzed by Tarjan in , is suited for incremental construction and management, differing from DFS's explicit traversal by avoiding full exploration for static checks.

References

  1. [1]
    [PDF] 223 Depth-first search - Introduction to Algorithms
    The strategy followed by depth-first search is, as its name implies, to search. “deeper” in the graph whenever possible. In depth-first search, ...
  2. [2]
    Depth-First Search and Linear Graph Algorithms | SIAM Journal on ...
    The value of depth-first search or “backtracking” as a technique for solving problems is illustrated by two examples.
  3. [3]
    Lecture 10: Depth-First Search | Introduction to Algorithms
    This class builds on the previous lecture of breadth-first search (BFS) by introducing depth-first search (DFS) and full-BFS and full-DFS.
  4. [4]
    Lecture 14: Depth-First Search (DFS), Topological Sort
    This lecture covers depth-first search, including edge classification, and how DFS is used for cycle detection and topological sort.
  5. [5]
    [PDF] Depth-First Search
    The Depth-First Search (DFS) algorithm is a special case of the generic graph-search algo- rithm, where each round visits the frontier vertex that is most ...
  6. [6]
    Introduction to Algorithms - MIT Press
    Introduction to Algorithms. Introduction to Algorithms. third edition. by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest ...
  7. [7]
    Backtrack Programming | Journal of the ACM - ACM Digital Library
    Backtrack Programming Authors: Solomon W. Golomb Solomon W. Golomb University of Southern California and Jet Propulsion Laboratory, Pasadena, Calif.
  8. [8]
    [PDF] effic'ientalgorithms for graphmanipulation - Stanford University
    Hopcroft, J., and R. Tarjan,. "Planarity testing in v log v steps, extended abstract," Stanford University CS 201, March 1971. -= ...
  9. [9]
    Depth-first search (DFS)
    In depth-first search the idea is to travel as deep as possible from neighbour to neighbour before backtracking. What determines how deep is possible is that ...Missing: formulation seminal paper
  10. [10]
    Introduction to Depth First Search Algorithm (DFS) - Baeldung
    Mar 24, 2023 · Nevertheless, in the iterative version, we must iterate over the neighbors in the reverse order. Therefore, we assume that G[u] returns the ...
  11. [11]
    Iterative Depth First Traversal of Graph - GeeksforGeeks
    Jul 23, 2025 · The idea is to fist push the given source into the stack. Then keep popping items from the stack while stack has items. Once we pop an item, we ...
  12. [12]
    DFS Recursive vs DFS Iterative [duplicate] - Stack Overflow
    Nov 20, 2014 · The recursive version uses the call stack while the iterative version performs exactly the same steps, but uses a user-defined stack instead of the call stack.What are the practical factors to consider when choosing between ...depth first search recursive or iterative - algorithm - Stack OverflowMore results from stackoverflow.com
  13. [13]
    None
    Summary of each segment:
  14. [14]
    [PDF] Depth-First Search
    If we require the topological ordering in a separate data structure, we can simply write the vertices into an array in reverse postorder, in O(V + E) time, as.
  15. [15]
    [PDF] Discrete Methods in Computer Science Spring 2025 Basics of Graph ...
    Recursive implementation of DFS. Initialize visited[v] = false for all nodes ... Total O(m + n). Graph Traversal. 31/34. Page 71. Iterative Implementation of DFS.<|control11|><|separator|>
  16. [16]
    [PDF] DFS Algorithm Pseudocode
    DFS Algorithm Pseudocode procedure DFS(G,v): for v ∈ V : explored[v] ← false end for for all v ∈ V do if not explored[v]:. DFS-visit(v) end procedure.
  17. [17]
    Depth First Search - Csl.mtu.edu
    There are two graph traversals, depth-first and breadth-first search. ... Derive a simpler pseudo-code in class. Algorithm DFS(graph G, Vertex v)
  18. [18]
    [PDF] Friday, May 26, 2017 - Stanford University
    Depth First Search (DFS): Iterative pseudocode dfs from v1 to v2: create a stack, s s.push(v1) while s is not empty: v = s.pop() if v has not been visited ...
  19. [19]
    [PDF] Notes 4 for CS 170 1 Depth-First Search - People @EECS
    Depth-first search takes O(n + e) steps on a graph with n vertices and e edges, because the algorithm performs at most some constant number of steps per each ...
  20. [20]
    [PDF] Depth-First Search and Directed Graphs
    A directed graph is acyclic (or a DAG) if it contains no. (directed) cycles. Question. Given a directed graph , can you detect if it has a cycle in linear time?
  21. [21]
    Operations on Binary Search Tree's
    Among them are the inorder, preorder and postorder traversal of nodes. Each of these traversal algorithms visit every node of the BST in a particular order.
  22. [22]
    Finding bridges in a graph in O(N+M) - CP-Algorithms
    Aug 25, 2025 · The implementation needs to distinguish three cases: when we go down the edge in DFS tree, when we find a back edge to an ancestor of the vertex ...
  23. [23]
    Detect Cycles in Directed Graphs Using DFS (Visualization)
    Learn how to detect cycles in directed graphs using DFS with optimized and brute force approaches. Includes Python, Java, and C++ code examples.
  24. [24]
    Topological Sort - USACO Guide
    Topological sort orders vertices of a directed acyclic graph so that each vertex is visited before its children, and for every edge u->v, u comes before v.
  25. [25]
    Depth-First Search in Python: Traversing Graphs and Trees
    Nov 3, 2024 · At its core, DFS works recursively, which means it solves the problem by repeatedly calling itself as it explores deeper into the structure.
  26. [26]
    Path Finding problems using Depth-First-Search DFS | - CoBlob
    Jul 12, 2021 · Pathfinding problems have many applications, from computer games, network routing to AI robots. If we want to explore unknown graphs and ...
  27. [27]
    15.2. Graph Algorithms — Programming for Mathematical Applications
    Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to a maze by only including nodes on the current path in the ...
  28. [28]
    [PDF] ROVEC: Runtime Optimization of Vectorized Expression Evaluation ...
    To simplify an expression, ROVEC first traverses the input expression via DFS to identify optimizable patterns. An optimizable pattern is an expression sub-tree ...
  29. [29]
    [PDF] Notes on Graph Algorithms Used in Optimizing Compilers
    Mar 31, 2013 · A depth-first walk is also often referred to as a depth-first traversal, or a depth-first search. The numbering of the nodes of G by a depth- ...
  30. [30]
    [PDF] Compiler Design Spring 2025 Recitation 8: Optimizations Solutions
    A known optimization to make this specific dataflow converge faster is to always iterate over the basic blocks (in the inner for loop) in postorder (DFS finish ...
  31. [31]
    [PDF] Lecture 7: Depth-First Search CLRS, section 22.3
    Can be thought of us processing 'wide' and then 'deep'. DFS will process the vertices first deep and then wide. After processing a vertex it recursively ...<|control11|><|separator|>
  32. [32]
    Time and Space Complexity of Adjacency Matrix and List - Baeldung
    Mar 18, 2024 · In this article, we'll use Big-O notation to describe the time and space complexity of methods that represent a graph.
  33. [33]
    Bi-directional and heuristic search in path problems
    Path-finding and Planning in a 3D Environment An Analysis Using Bidirectional Versions of Dijkstra's, Weighted A*, and Greedy Best First Search Algorithms.
  34. [34]
    [PDF] A Brief History and Recent Achievements in Bidirectional Search
    This paper is designed to provide an accessible overview of the recent research in bidi- rectional search in the context of the broader efforts over the last 50 ...<|control11|><|separator|>
  35. [35]
    [PDF] Parallel Depth-First Search for Directed Acyclic Graphs
    Abstract. Depth-First Search (DFS) is a pervasive algorithm, often used as a build- ing block for topological sort, connectivity and planarity testing, ...
  36. [36]
    [PDF] PARALLEL DEPTH FIRST SEARCH, PART II: - ANALYSIS
    Much of the analysis presented in this paper is applicable to other parallel algorithms in which work is dynamically shared between different processors (e.g., ...
  37. [37]
    (PDF) The Nature of Breadth-First Search - ResearchGate
    Breadth-first search (BFS) is one of the oldest and most fundamental graph traversal algorithms, influencing many other graph algorithms.Missing: seminal | Show results with:seminal
  38. [38]
    [PDF] Depth-First Iterative-Deepening: An Optimal Admissible Tree Search*
    Korf, R.E., Learning to Solve Problems by Searching for Macro- Operators (Pit tman, London,. 1985). ... Korf, R.E., Iterative-deepening-A': an optimal admissible ...Missing: URL | Show results with:URL
  39. [39]
    Backtrack Programming | Semantic Scholar
    Backtrack Programming · S. Golomb, L. D. Baumert · Published in JACM 1 October 1965 · Computer Science · J. ACM.