Article start
DSA Course: Interview Patterns and Problem Solving
Module 7: Graphs

Shortest Path in Unweighted Graph: BFS Distance Pattern

Use BFS layers to find the fewest edges between two nodes.

May 29, 2026·24

Learning Outcome

After this lesson, you should be able to use BFS levels as distance in an unweighted graph.

Problem Statement

Given n nodes, undirected edges, a source, and a destination, return the shortest number of edges from source to destination.

InputOutputWhy
n = 5, edges = [[0,1],[1,2],[0,3],[3,4]], src = 0, dst = 42The shortest path is 0 to 3 to 4.

Brute Force Approach

Use DFS to enumerate all paths and then choose the shortest. DFS may explore long paths before short paths.

Optimized Approach

Build an adjacency list and run BFS from the source. The first time a node is reached, its distance is shortest.

Exact Pseudocode

build adjacency list
queue = [(source, 0)]
mark source as seen
while queue not empty:
  node, distance = pop front
  if node is destination:
    return distance
  for neighbor in adj[node]:
    if neighbor is unseen:
      mark neighbor as seen
      push (neighbor, distance + 1)
return -1

Reference Code

from collections import deque

class Solution:
    def shortestPath(self, n, edges, src, dst):
        adj = [[] for _ in range(n)]
        for a, b in edges:
            adj[a].append(b)
            adj[b].append(a)

        q = deque([(src, 0)])
        seen = {src}

        while q:
            node, dist = q.popleft()
            if node == dst:
                return dist
            for nei in adj[node]:
                if nei not in seen:
                    seen.add(nei)
                    q.append((nei, dist + 1))
        return -1

Sample Dry Run

StepStateResult
Startqueue = [(0,0)]seen = {0}
Pop 0Add 1 and 3 with distance 1queue = [(1,1),(3,1)]
Pop 3Add 4 with distance 2queue includes destination
Pop 4Destination reachedreturn 2

Complexity

MeasureValueReason
TimeO(n + e)BFS processes each node and edge at most once.
SpaceO(n + e)Adjacency, queue, and seen set take linear space.

Edge Cases

  • If source equals destination, return 0.
  • If destination is unreachable, return -1.
  • This works for unweighted graphs, not weighted shortest path.

Interview Checklist

  • Mark nodes when enqueued, not when popped.
  • Store distance with each node or level by level.
  • Return as soon as destination is popped or first reached.

FAQs

Why does BFS give shortest distance?

BFS explores all nodes at distance d before any node at distance d + 1.

Can DFS solve this?

DFS can find a path, but it does not naturally guarantee the shortest unweighted path.

What is the core pattern?

BFS layer distance.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.