Minimum Hop Count in a Binary Adjacency Matrix

Medium · Coding & Algorithms · Forward Deploy Engineer · Technical Screen

Problem Statement

An undirected, unweighted simple network of n nodes numbered 0 through n - 1 is given as an n x n binary grid adj_matrix. Entry adj_matrix[u][v] is 1 when a direct link connects node u and node v, and 0 when no direct link exists between them.

Given adj_matrix, a starting node src, and a destination node dst, return the minimum number of links (hops) along any route from src to dst.

def shortest_distance(adj_matrix: list[list[int]], src: int, dst: int) -> int:
  • If src == dst, zero links are traversed, so return 0.
  • If no sequence of links connects src to dst, return -1.

Examples

Example 1

Input:
adj_matrix = [
  [0, 1, 0, 1, 0],
  [1, 0, 1, 0, 0],
  [0, 1, 0, 0, 1],
  [1, 0, 0, 0, 1],
  [0, 0, 1, 1, 0]
]
src = 0, dst = 4
Output: 2

Walk-through: Node 0 can reach node 4 along 0 -> 1 -> 2 -> 4 (3 hops) or along the shorter route 0 -> 3 -> 4 (2 hops), so the minimum hop count is 2.

Example 2

Input:
adj_matrix = [
  [0, 0, 1, 0],
  [0, 0, 0, 1],
  [1, 0, 0, 0],
  [0, 1, 0, 0]
]
src = 2, dst = 1
Output: -1

Walk-through: Nodes {0, 2} and {1, 3} form two separate components with no link between them, making 1 unreachable from 2.

Example 3

Input:
adj_matrix = [
  [0, 1, 0],
  [1, 0, 1],
  [0, 1, 0]
]
src = 2, dst = 2
Output: 0

Walk-through: Start and destination coincide at node 2, requiring 0 hops.

Constraints

  • 1 <= n <= 1000, where n = len(adj_matrix) and every row has length n
  • 0 <= src, dst < n
  • adj_matrix[u][v] is either 0 or 1 for all 0 <= u, v < n
  • adj_matrix[u][u] == 0 for all 0 <= u < n (no self-loops)
  • adj_matrix[u][v] == adj_matrix[v][u] for all 0 <= u, v < n (symmetric undirected links)

Step-by-step walkthrough

  1. Understand the input: reading links from an adjacency matrix

    We are given an undirected, unweighted graph on n nodes (0 through n - 1). Instead of an edge list, the graph arrives as an n x n adjacency matrix — a 2D table where cell adj_matrix[u][v] is 1 if nodes u and v share a direct link, and 0 otherwise.

    Here is Example 1 as both a picture and its 5 x 5 matrix:

    Graph:                       adj_matrix (rows = u, cols = v):
        0 --- 1 --- 2                v=0  v=1  v=2  v=3  v=4
        |           |          u=0 [  0,   1,   0,   1,   0 ]  -> 0 connects to 1, 3
        3 --------- 4          u=1 [  1,   0,   1,   0,   0 ]  -> 1 connects to 0, 2
                               u=2 [  0,   1,   0,   0,   1 ]  -> 2 connects to 1, 4
                               u=3 [  1,   0,   0,   0,   1 ]  -> 3 connects to 0, 4
                               u=4 [  0,   0,   1,   1,   0 ]  -> 4 connects to 2, 3
    

    Our goal is to find the minimum number of hops on any route from src to dst:

    • Return 0 if src == dst (zero hops needed).
    • Return -1 if dst cannot be reached from src.

    Because n <= 1000, the matrix has up to 1,000,000 entries, so an O(n^2) algorithm fits comfortably.

  2. Why plain DFS fails and why BFS finds the shortest route

    Every link costs the exact same 1 hop, so "shortest route" means "fewest hops." What happens if we just walk forward along the first unused neighbor we see (Depth-First Search, or DFS) until we hit dst?

    Look at Example 1 (src = 0, dst = 4): if DFS starts at 0 and inspects neighbor 1 first, it walks 0 -> 1 -> 2 -> 4 (3 hops) and misses the shorter 0 -> 3 -> 4 route (2 hops)! Fixing DFS by trying every simple path takes exponential time on dense graphs, and running an all-pairs algorithm like Floyd-Warshall takes O(n^3) (10^9 operations at n = 1000), which is too slow when we only care about one (src, dst) pair.

    Instead, we use Breadth-First Search (BFS) — a search that explores the graph in concentric rings (layers) outward from src:

    • Layer 0: src itself (0 hops).
    • Layer 1: all direct neighbors of src (1 hop).
    • Layer 2: all unvisited neighbors of Layer 1 (2 hops), and so on.

    To process vertices strictly in layer order, we keep discovered vertices in a FIFO queue (first-in, first-out, implemented with collections.deque): every Layer k vertex enters the back of the line before any Layer k + 1 vertex, so all Layer k vertices are popped from the front before Layer k + 1 begins. Consequently, the very first time BFS discovers a vertex, it has found a shortest path to it.

  3. Mark vertices on enqueue, not on dequeue

    There is one classic BFS trap to avoid: when do we mark a vertex as visited?

    Suppose vertex 0 connects to 1 and 2, and both 1 and 2 connect to 3. Look at what happens if we wait until a vertex is popped from the queue to mark it visited:

    Mark on DEQUEUE (buggy / bloated):          Mark on ENQUEUE (clean):
    Pop 0 -> push 1, push 2                     Pop 0 -> mark 1 (d=1), mark 2 (d=1), push 1, 2
    Pop 1 -> 3 looks unvisited! push 3          Pop 1 -> mark 3 (d=2), push 3
    Pop 2 -> 3 STILL looks unvisited! push 3    Pop 2 -> 3 already has d=2 != -1, skip!
    Queue gets duplicate copies of 3!           Every vertex enters the queue at most once.
    

    In a dense 1000-vertex graph, waiting until dequeue can stuff O(n^2) duplicate entries into the queue. Marking on enqueue guarantees every vertex enters the queue at most once.

    Better yet, one integer list distance of length n can track both "have we discovered v?" and "how far is v from src?":

    • distance[v] == -1 means v has not been discovered yet.
    • distance[v] >= 0 is the final shortest-path hop count from src to v.
    from collections import deque
    
    num_vertices = len(adj_matrix)
    distance = [-1] * num_vertices
    distance[src] = 0
    queue = deque([src])
    
  4. Scan matrix rows to expand each BFS layer

    How do we find all neighbors of vertex current when the graph is an adjacency matrix? Unlike an adjacency list, there is no pre-built list of neighbors — we scan all num_vertices columns of adj_matrix[current] and check where row[neighbor] == 1.

    Two small details make the loop fast and clean:

    1. Use deque.popleft(), which removes the front item in O(1) time (list.pop(0) shifts every remaining element and costs O(n) per pop).
    2. Check if neighbor == dst: right when neighbor is discovered. Because distance[neighbor] is already optimal at discovery time, we can return immediately without waiting for dst to reach the front of the queue.
    def shortest_distance(adj_matrix: list[list[int]], src: int, dst: int) -> int:
        # Phase 1: Handle the zero-hop case immediately before starting a search.
        if src == dst:
            return 0
    
        num_vertices = len(adj_matrix)
    
        # distance[v]: fewest edges from src to v, or -1 if v has not been discovered yet.
        # Example shape: [0, 1, -1, 1, -1] means vertex 0 is src, 1 and 3 are 1 hop away, 2 and 4 are unvisited.
        distance = [-1] * num_vertices
        distance[src] = 0
    
        # queue: FIFO queue of discovered vertex indices waiting to have their matrix row scanned.
        queue = deque([src])
    
        # Phase 2: Expand outward one hop (BFS layer) at a time.
        while queue:
            current = queue.popleft()
            row = adj_matrix[current]
    
            # Scan all columns of `row` to find every neighbor connected to `current` by an edge.
            for neighbor in range(num_vertices):
                if row[neighbor] == 1 and distance[neighbor] == -1:
                    # Record distance on enqueue (not dequeue) so each vertex enters the queue
                    # at most once, and the first discovery is guaranteed to be a shortest path.
                    distance[neighbor] = distance[current] + 1
                    if neighbor == dst:
                        return distance[neighbor]
                    queue.append(neighbor)
    
        # Phase 3: The queue emptied without reaching dst, so no path exists.
        return -1
    
  5. Trace the examples step by step

    Let's trace Example 1 (src = 0, dst = 4 on the 5-node graph with links 0-1, 1-2, 2-4, 0-3, 3-4):

    Step   Pop   Row `adj_matrix[current]`   Newly discovered   `distance` after        `queue` after
    ----   ---   -------------------------   ----------------   ---------------------   -------------
    init    -                -               0 (src)            [0, -1, -1, -1, -1]     deque([0])
     1      0    [0, 1, 0, 1, 0]             1 (d=1), 3 (d=1)   [0,  1, -1,  1, -1]     deque([1, 3])
     2      1    [1, 0, 1, 0, 0]             0 skipped, 2 (d=2) [0,  1,  2,  1, -1]     deque([3, 2])
     3      3    [1, 0, 0, 0, 1]             0 skipped,         [0,  1,  2,  1,  2]     4 == dst -> return 2!
                                             4 (d=2 == dst!)
    
    • Example 2 (src = 2, dst = 1, separate links 0-2 and 1-3): 2 enqueues 0 (d = 1), 0 scans [0, 0, 1, 0] and skips 2 because distance[2] == 0 != -1, the queue empties, and Phase 3 returns -1.
    • Example 3 (src = 2, dst = 2): Phase 1 sees src == dst and immediately returns 0.
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def shortest_distance(adj_matrix: list[list[int]], src: int, dst: int) -> int:
        # Phase 1: Handle the zero-hop case immediately before starting a search.
        if src == dst:
            return 0
    
        num_vertices = len(adj_matrix)
    
        # distance[v]: fewest edges from src to v, or -1 if v has not been discovered yet.
        # Example shape: [0, 1, -1, 1, -1] means vertex 0 is src, 1 and 3 are 1 hop away, 2 and 4 are unvisited.
        distance = [-1] * num_vertices
        distance[src] = 0
    
        # queue: FIFO queue of discovered vertex indices waiting to have their matrix row scanned.
        queue = deque([src])
    
        # Phase 2: Expand outward one hop (BFS layer) at a time.
        while queue:
            current = queue.popleft()
            row = adj_matrix[current]
    
            # Scan all columns of `row` to find every neighbor connected to `current` by an edge.
            for neighbor in range(num_vertices):
                if row[neighbor] == 1 and distance[neighbor] == -1:
                    # Record distance on enqueue (not dequeue) so each vertex enters the queue
                    # at most once, and the first discovery is guaranteed to be a shortest path.
                    distance[neighbor] = distance[current] + 1
                    if neighbor == dst:
                        return distance[neighbor]
                    queue.append(neighbor)
    
        # Phase 3: The queue emptied without reaching dst, so no path exists.
        return -1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine dropping a pebble at node src in a network of canals: the ripple reaches every direct neighbor in 1 second, every neighbor's neighbor in 2 seconds, and so on at a steady pace of one link per second. Breadth-First Search (BFS) — a graph traversal that explores vertices ring by ring in increasing order of hop count — works just like that ripple. By keeping discovered vertices in a FIFO queue (a first-in, first-out line where items leave in the exact order they arrived), we finish all distance-d vertices before expanding any distance-(d + 1) vertex, so the very first time the ripple touches dst is guaranteed to be the shortest route.

Why do the obvious alternatives fall short? A Depth-First Search (DFS) — which plunges deep down one branch before backtracking — might return the first route it stumbles across (3 hops via 0 -> 1 -> 2 -> 4) instead of a 2-hop shortcut (0 -> 3 -> 4), while trying every simple path takes exponential time on dense graphs. On the other hand, an all-pairs shortest-path algorithm like Floyd-Warshall computes distances between every pair of vertices in O(n^3) time (10^9 operations when n = 1000), doing n times more work than necessary for a single (src, dst) query.

Here is how BFS finds the hop count from src = 0 to dst = 4 on Example 1's 5 x 5 adjacency matrix (a 0/1 table where adj_matrix[u][v] == 1 means a link connects u and v):

Links: 0-1, 1-2, 2-4, 0-3, 3-4

Start:  distance = [0, -1, -1, -1, -1],  queue = [0]
Pop 0:  row 0 is [0, 1, 0, 1, 0] -> discover 1 (dist 1) and 3 (dist 1)
        distance = [0,  1, -1,  1, -1],  queue = [1, 3]
Pop 1:  row 1 is [1, 0, 1, 0, 0] -> 0 already visited; discover 2 (dist 2)
        distance = [0,  1,  2,  1, -1],  queue = [3, 2]
Pop 3:  row 3 is [1, 0, 0, 0, 1] -> 0 already visited; discover 4 (dist 2 == dst!)
        Return 2 immediately.

Complexity

  • Time: O(n^2), where n is the number of vertices. Because distance[neighbor] is set from -1 to a non-negative integer the moment neighbor enters the queue, each of the n vertices is enqueued and popped at most once. Popping a vertex scans all n columns of its matrix row (O(n) work), giving at most n * n = O(n^2) operations in total — matching the number of cells in the input matrix.
  • Space: O(n) auxiliary memory beyond the input matrix. Both the distance array of length n and the deque (which holds at most n distinct vertices at any moment) grow linearly with the vertex count.

Edge cases

  • src == dst: Handled before the loop and returns 0 immediately; this also covers a single-vertex graph [[0]].
  • Disconnected components: A connected component is a maximal group of vertices that can reach one another. When src and dst lie in different components (as in Example 2, {0, 2} vs. {1, 3}), the queue empties and the function returns -1.
  • Direct link between src and dst: Found on the very first row scan (current == src), returning 1.
  • Shorter route through higher-numbered indices: Even when 0 links to 1 (0-1-2-4) and also to 3 (0-3-4), BFS explores all 1-hop neighbors (1 and 3) before any 2-hop neighbor, finding 0 -> 3 -> 4 (2 hops) instead of 3.
  • Dense component without dst: Every reachable vertex is popped and its entire n-element row is scanned before returning -1, exercising the full O(n^2) worst case.

Common mistakes

  • Marking vertices visited on dequeue instead of enqueue: If distance[neighbor] is only set when neighbor is popped, multiple Layer d neighbors will push duplicate copies of the same Layer d + 1 vertex into the queue, bloating the queue to O(n^2) entries on dense graphs.
  • Forgetting to mark src before starting (distance[src] = 0): Since links are undirected (adj_matrix[neighbor][src] == 1), src's neighbors will immediately re-discover src at distance 2 if distance[src] is left at -1.
  • Using list.pop(0) instead of collections.deque.popleft(): Removing index 0 from a Python list shifts every remaining element one slot left (O(n) per pop), whereas deque.popleft() is O(1).
  • Pre-converting adj_matrix into an adjacency list for a single query: Building an adjacency list already reads all n^2 matrix cells (O(n^2) time) and allocates up to O(n^2) extra memory, so it only pays off when answering many queries on the same static graph.
  • Returning 0 or float("inf") when unreachable: 0 means src == dst; unreachable pairs must return -1.

Alternative approaches

  • Bidirectional BFS: Run two simultaneous layer-by-layer BFS frontiers — one forward from src and one backward from dst — stopping as soon as the frontiers meet (detailed in the third follow-up below).
  • Precomputed adjacency list + BFS: Spend O(n^2) once to extract neighbor lists, then answer each (src, dst) query in O(n + m) time where m is the link count. Ideal when thousands of queries hit the same matrix.
  • Floyd-Warshall: Dynamic programming over intermediate vertices 0 .. n - 1 in O(n^3) time and O(n^2) space. Too slow for one query at n = 1000, but concise as a randomized test oracle on tiny graphs.

Follow-up questions

  • When a graph has very few edges relative to its vertex count, how does BFS runtime differ between a matrix representation and neighbor lists? A sparse graph is a graph whose edge count m is much smaller than the maximum possible n * (n - 1) / 2 (for example, m proportional to n). On an adjacency matrix, BFS still takes O(n^2) worst-case time because popping any vertex scans all n columns of its row even when almost every entry is 0. With neighbor lists (an adjacency list storing only actual neighbors per vertex), BFS visits only existing edges and runs in O(n + m) time and O(n + m) space — dropping from O(n^2) to O(n) on sparse graphs.
  • What extra bookkeeping is required to reconstruct the full vertex-by-vertex shortest route instead of returning only its length? Allocate an array parent = [-1] * num_vertices, and at the exact moment neighbor is first discovered from current, set parent[neighbor] = current. Once dst is reached, trace backward from dst via v = parent[v] until reaching src, collect each vertex in a list, and reverse that list before returning it. This uses O(n) extra memory and O(route_length) reconstruction time, returning [] when dst is unreachable.
  • How does searching simultaneously from both endpoints speed up typical queries, and when is it safe to stop? Bidirectional BFS runs one frontier outward from src (dist_src) and a second frontier outward from dst (dist_dst), expanding one complete BFS layer of whichever queue is currently smaller on each step. With average branching factor b and shortest distance d, a single BFS visits roughly b^d vertices whereas two half-radius searches visit roughly 2 * b^(d / 2) vertices — exponentially fewer row scans. Because both frontiers advance strictly one full layer at a time, if dist_src (covering radius r_src) and dist_dst (covering radius r_dst) had no overlap prior to this layer, no path shorter than r_src + r_dst + 1 exists; thus the very first newly discovered vertex v in the expanded layer that already has a recorded distance on the opposite side yields the exact minimum dist_src[v] + dist_dst[v] (and if either queue empties first, return -1).

Follow-up questions

Similar questions

More BCG interview questions

All 1 BCG questions →