Depth-First Search (DFS) algorithm DFS is an algorithm for traversing or searching tree or graph data structures. It starts at a chosen node and explores as far as possible along each branch before backtracking.

Time Complexity: O(V + E) where V is vertices and E is edges Space Complexity: O(V)

Example

const graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
};
DFS.traverse(graph, 'A'); // returns nodes in DFS order
DFS.findPath(graph, 'A', 'F'); // returns a path from A to F

Hierarchy

  • DFS

Constructors

Methods

  • Finds a path between two nodes using DFS

    Parameters

    • graph: {
          [key: string]: string[];
      }

      adjacency list representation of the graph

      • [key: string]: string[]
    • start: string

      starting node

    • end: string

      ending node

    Returns null | string[]

    array representing a path, or null if no path exists

  • Finds a path between two nodes using DFS (recursive)

    Parameters

    • graph: {
          [key: string]: string[];
      }

      adjacency list representation of the graph

      • [key: string]: string[]
    • start: string

      starting node

    • end: string

      ending node

    Returns null | string[]

    array representing a path, or null if no path exists

  • Detects if a graph has a cycle using DFS

    Parameters

    • graph: {
          [key: string]: string[];
      }

      adjacency list representation of the graph

      • [key: string]: string[]

    Returns boolean

    true if the graph has a cycle, false otherwise

  • Checks if there is a path between two nodes

    Parameters

    • graph: {
          [key: string]: string[];
      }

      adjacency list representation of the graph

      • [key: string]: string[]
    • start: string

      starting node

    • end: string

      ending node

    Returns boolean

    true if a path exists, false otherwise

  • Performs DFS traversal starting from a given node (iterative)

    Parameters

    • graph: {
          [key: string]: string[];
      }

      adjacency list representation of the graph

      • [key: string]: string[]
    • start: string

      starting node

    Returns string[]

    array of nodes in DFS order

  • Performs DFS traversal starting from a given node (recursive)

    Parameters

    • graph: {
          [key: string]: string[];
      }

      adjacency list representation of the graph

      • [key: string]: string[]
    • start: string

      starting node

    Returns string[]

    array of nodes in DFS order

Generated using TypeDoc