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 return0. - If no sequence of links connects
srctodst, 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, wheren = len(adj_matrix)and every row has lengthn0 <= src, dst < nadj_matrix[u][v]is either0or1for all0 <= u, v < nadj_matrix[u][u] == 0for all0 <= u < n(no self-loops)adj_matrix[u][v] == adj_matrix[v][u]for all0 <= u, v < n(symmetric undirected links)
Step-by-step walkthrough
Understand the input: reading links from an adjacency matrix
We are given an undirected, unweighted graph on
nnodes (0throughn - 1). Instead of an edge list, the graph arrives as ann x nadjacency matrix — a 2D table where celladj_matrix[u][v]is1if nodesuandvshare a direct link, and0otherwise.Here is Example 1 as both a picture and its
5 x 5matrix: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, 3Our goal is to find the minimum number of hops on any route from
srctodst:- Return
0ifsrc == dst(zero hops needed). - Return
-1ifdstcannot be reached fromsrc.
Because
n <= 1000, the matrix has up to1,000,000entries, so anO(n^2)algorithm fits comfortably.- Return
Why plain DFS fails and why BFS finds the shortest route
Every link costs the exact same
1hop, 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 hitdst?Look at Example 1 (
src = 0,dst = 4): if DFS starts at0and inspects neighbor1first, it walks0 -> 1 -> 2 -> 4(3hops) and misses the shorter0 -> 3 -> 4route (2hops)! Fixing DFS by trying every simple path takes exponential time on dense graphs, and running an all-pairs algorithm like Floyd-Warshall takesO(n^3)(10^9operations atn = 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:
srcitself (0hops). - Layer 1: all direct neighbors of
src(1hop). - Layer 2: all unvisited neighbors of Layer 1 (
2hops), 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 Layerkvertex enters the back of the line before any Layerk + 1vertex, so all Layerkvertices are popped from the front before Layerk + 1begins. Consequently, the very first time BFS discovers a vertex, it has found a shortest path to it.- Layer 0:
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
0connects to1and2, and both1and2connect to3. 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 stuffO(n^2)duplicate entries into the queue. Marking on enqueue guarantees every vertex enters the queue at most once.Better yet, one integer list
distanceof lengthncan track both "have we discoveredv?" and "how far isvfromsrc?":distance[v] == -1meansvhas not been discovered yet.distance[v] >= 0is the final shortest-path hop count fromsrctov.
from collections import deque num_vertices = len(adj_matrix) distance = [-1] * num_vertices distance[src] = 0 queue = deque([src])Scan matrix rows to expand each BFS layer
How do we find all neighbors of vertex
currentwhen the graph is an adjacency matrix? Unlike an adjacency list, there is no pre-built list of neighbors — we scan allnum_verticescolumns ofadj_matrix[current]and check whererow[neighbor] == 1.Two small details make the loop fast and clean:
- Use
deque.popleft(), which removes the front item inO(1)time (list.pop(0)shifts every remaining element and costsO(n)per pop). - Check
if neighbor == dst:right whenneighboris discovered. Becausedistance[neighbor]is already optimal at discovery time, we can return immediately without waiting fordstto 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- Use
Trace the examples step by step
Let's trace Example 1 (
src = 0,dst = 4on the 5-node graph with links0-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 links0-2and1-3):2enqueues0(d = 1),0scans[0, 0, 1, 0]and skips2becausedistance[2] == 0 != -1, the queue empties, and Phase 3 returns-1. - Example 3 (
src = 2,dst = 2): Phase 1 seessrc == dstand immediately returns0.
- Example 2 (
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), wherenis the number of vertices. Becausedistance[neighbor]is set from-1to a non-negative integer the momentneighborenters the queue, each of thenvertices is enqueued and popped at most once. Popping a vertex scans allncolumns of its matrix row (O(n)work), giving at mostn * 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 thedistancearray of lengthnand thedeque(which holds at mostndistinct vertices at any moment) grow linearly with the vertex count.
Edge cases
src == dst: Handled before the loop and returns0immediately; 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
srcanddstlie in different components (as in Example 2,{0, 2}vs.{1, 3}), the queue empties and the function returns-1. - Direct link between
srcanddst: Found on the very first row scan (current == src), returning1. - Shorter route through higher-numbered indices: Even when
0links to1(0-1-2-4) and also to3(0-3-4), BFS explores all1-hop neighbors (1and3) before any2-hop neighbor, finding0 -> 3 -> 4(2hops) instead of3. - Dense component without
dst: Every reachable vertex is popped and its entiren-element row is scanned before returning-1, exercising the fullO(n^2)worst case.
Common mistakes
- Marking vertices visited on dequeue instead of enqueue: If
distance[neighbor]is only set whenneighboris popped, multiple Layerdneighbors will push duplicate copies of the same Layerd + 1vertex into the queue, bloating the queue toO(n^2)entries on dense graphs. - Forgetting to mark
srcbefore starting (distance[src] = 0): Since links are undirected (adj_matrix[neighbor][src] == 1),src's neighbors will immediately re-discoversrcat distance2ifdistance[src]is left at-1. - Using
list.pop(0)instead ofcollections.deque.popleft(): Removing index0from a Pythonlistshifts every remaining element one slot left (O(n)per pop), whereasdeque.popleft()isO(1). - Pre-converting
adj_matrixinto an adjacency list for a single query: Building an adjacency list already reads alln^2matrix cells (O(n^2)time) and allocates up toO(n^2)extra memory, so it only pays off when answering many queries on the same static graph. - Returning
0orfloat("inf")when unreachable:0meanssrc == dst; unreachable pairs must return-1.
Alternative approaches
- Bidirectional BFS: Run two simultaneous layer-by-layer BFS frontiers — one forward from
srcand one backward fromdst— 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 inO(n + m)time wheremis the link count. Ideal when thousands of queries hit the same matrix. - Floyd-Warshall: Dynamic programming over intermediate vertices
0 .. n - 1inO(n^3)time andO(n^2)space. Too slow for one query atn = 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
mis much smaller than the maximum possiblen * (n - 1) / 2(for example,mproportional ton). On an adjacency matrix, BFS still takesO(n^2)worst-case time because popping any vertex scans allncolumns of its row even when almost every entry is0. With neighbor lists (an adjacency list storing only actual neighbors per vertex), BFS visits only existing edges and runs inO(n + m)time andO(n + m)space — dropping fromO(n^2)toO(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 momentneighboris first discovered fromcurrent, setparent[neighbor] = current. Oncedstis reached, trace backward fromdstviav = parent[v]until reachingsrc, collect each vertex in a list, and reverse that list before returning it. This usesO(n)extra memory andO(route_length)reconstruction time, returning[]whendstis 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 fromdst(dist_dst), expanding one complete BFS layer of whichever queue is currently smaller on each step. With average branching factorband shortest distanced, a single BFS visits roughlyb^dvertices whereas two half-radius searches visit roughly2 * b^(d / 2)vertices — exponentially fewer row scans. Because both frontiers advance strictly one full layer at a time, ifdist_src(covering radiusr_src) anddist_dst(covering radiusr_dst) had no overlap prior to this layer, no path shorter thanr_src + r_dst + 1exists; thus the very first newly discovered vertexvin the expanded layer that already has a recorded distance on the opposite side yields the exact minimumdist_src[v] + dist_dst[v](and if either queue empties first, return-1).
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?
- What extra bookkeeping is required to reconstruct the full vertex-by-vertex shortest route instead of returning only its length?
- How does searching simultaneously from both endpoints speed up typical queries, and when is it safe to stop?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array