Breadth-First Search (BFS) algorithm BFS is an algorithm for traversing or searching tree or graph data structures. It starts at a chosen node and explores all neighbor nodes at the present depth before moving on to nodes at the next depth level.

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']
};
BFS.traverse(graph, 'A'); // returns ['A', 'B', 'C', 'D', 'E', 'F']
BFS.findPath(graph, 'A', 'F'); // returns ['A', 'C', 'F']

Hierarchy

  • BFS

Constructors

Methods

  • Finds shortest path between two nodes using BFS

    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 the shortest path, or null if no path exists

  • 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

  • Finds all nodes at a given distance from the start node

    Parameters

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

      adjacency list representation of the graph

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

      starting node

    • distance: number

      distance from start node

    Returns string[]

    array of nodes at the given distance

  • Performs BFS traversal starting from a given node

    Parameters

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

      adjacency list representation of the graph

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

      starting node

    Returns string[]

    array of nodes in BFS order

Generated using TypeDoc