DSA
    beginner

    Breadth-First Search (BFS)

    Software Engineer path · lesson 21 of 99
    time O(V + E)
    space O(V)
    Maze:
    Tap or drag on the grid to
    Algorithm

    Switch and compare the expanded-cells count.

    Show costs (g)
    SG
    ExpandingFrontierExpandedNeighbour checkedShortest path

    Start at (4,1), goal (4,11).

    Code (running line highlighted)
    1. 1queue = [start]; seen = {start}
    2. 2while queue:
    3. 3 cell = queue.popleft() # oldest first
    4. 4 if cell == goal: return path
    5. 5 for nb in neighbours(cell):
    6. 6 if nb not seen: seen.add(nb); parent[nb] = cell; queue.append(nb)
    7. 7return "no path"
    Cells expanded
    0 / 108
    Frontier pushes
    1 / 110
    Invariant: The queue holds cells in order of distance from the start, never more than one step apart.

    Tap any element in the diagram to inspect its state at this step.

    1 / 219

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Breadth-first, level by level

    Sequence

    Order the steps of BFS from a source node.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Does BFS guarantee the shortest path?

    The short version

    Think of dropping a stone in a calm pond. Ripples spread out in circles, reaching everything at distance 1, then distance 2. BFS explores 'ripples' layer by layer.

    In more depth

    Layer by Layer

    Breadth-First Search (BFS) is like a wave spreading out from a pebble dropped in water. It explores the graph layer by layer: first all neighbors at distance 1, then all neighbors at distance 2, and so on.

    The Queue:

    BFS uses a Queue (FIFO) data structure.

    1.Add the starting node to the queue.
    2.While the queue is not empty:
    Dequeue a node.
    Visits all its unvisited neighbors and enqueue them.

    Shortest Path Guarantee

    Because BFS explores layers sequentially, the first time it reaches a target node, it is guaranteed to be via the shortest path (in an unweighted graph).

    When to reach for this

    • Find the **Shortest Path** in an **Unweighted Graph** or Grid
    • Level Order Traversal of a Tree
    • Find all nodes connected to a source (Connected Components)
    • State space search where the cost of each move is equal

    Interview Questions

    Amazon
    LinkedIn
    Google
    Amazon
    Microsoft
    Meta
    Uber
    Microsoft
    Google
    Amazon
    Bloomberg
    Netflix
    LinkedIn
    Meta
    Google

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required