Minimum Hops Between Nodes in a Matrix-Represented Graph
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests ability to implement BFS on an undirected unweighted graph stored as an adjacency matrix to find the fewest edges between two nodes.
Minimum Hops Between Two Nodes
You have an undirected, unweighted graph of n nodes numbered 0 through n - 1. The graph is described by an n x n binary matrix called conn, where conn[i][j] == 1 means there is a direct edge between node i and node j, and conn[i][j] == 0 means there is no such edge.
Given a starting node start and a target node end, return the fewest number of edges that must be traversed to travel from start to end.
- If
startandendare the same node, the answer is0. - If no path connects
starttoend, return-1.
Input
conn: A 2D list of integers with dimensionsn x n. Every entry is either0or1. The matrix is symmetric (conn[i][j] == conn[j][i]) and has no self-loops (conn[i][i] == 0).start: An integer index of the source node (0 <= start < n).end: An integer index of the destination node (0 <= end < n).
Output
An integer: the minimum number of edges on any path from start to end, or -1 if the two nodes belong to different connected components.
Constraints
1 <= n <= 10000 <= start, end < nconn[i][i] == 0for all0 <= i < nconn[i][j] == conn[j][i]for all0 <= i, j < n- Each entry
conn[i][j]is0or1
Examples
Example 1
Input: min_hops([[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]], 0, 3)
Output: 2
Example 2
Input: min_hops([[0, 1, 0], [1, 0, 0], [0, 0, 0]], 0, 2)
Output: -1
Example 3
Input: min_hops([[0, 1], [1, 0]], 1, 1)
Output: 0
Hints
Hint 1
The graph is unweighted, so the shortest path by edge count is the one BFS reaches first — not DFS, and not Dijkstra. Think about what BFS explores at each 'layer'.
Hint 2
When you dequeue a node, scan its entire row in `conn` to find neighbors. Mark a neighbor as visited the moment you add it to the queue, not when you pop it, to avoid adding the same node multiple times.
Hint 3
Handle `start == end` before the BFS loop starts — the loop only checks newly discovered neighbors, so it would miss this case and return the wrong answer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why BFS
Every edge in this graph has the same weight (1), so the path with the fewest edges is the shortest path. BFS is the right tool: it explores nodes layer by layer, where each layer corresponds to nodes exactly d edges from the source. The first time BFS reaches the destination, that layer number is the answer. DFS finds a path but not necessarily the shortest one. Dijkstra works but adds unnecessary overhead when all edges are equal.
How the algorithm works
-
Base case. If
start == end, return0immediately. The main loop only checks newly discovered neighbors, so it would never fire for the source node itself. -
Initialization. Create a
distarray of lengthn, filled with-1to mean "not yet visited". Setdist[start] = 0and putstartin a queue. -
BFS loop. While the queue is non-empty, dequeue a node and compute
next_dist = dist[node] + 1. Scan every position in that node's row ofconn. For each position whereconn[node][neighbor] == 1anddist[neighbor] == -1:- If
neighboris the destination, returnnext_distimmediately. - Otherwise, set
dist[neighbor] = next_distand enqueue it.
- If
-
No path. If the queue drains without finding
end, they are in different components — return-1.
Why marking on enqueue matters
A node gets its distance recorded the moment it enters the queue, not when it is dequeued. This guarantees each node enters the queue at most once. Marking on dequeue instead would allow the same node to be added multiple times, potentially blowing the queue up to O(n²) entries in a dense graph.
Correctness argument
BFS maintains the invariant that the queue holds nodes in non-decreasing order of distance. When a node u is dequeued with distance d, any undiscovered neighbor v must be at distance d + 1. If v were closer, it would have been discovered while processing an earlier layer and would already be marked. Therefore the first time end is reached, the recorded distance is optimal.
Complexity
- Time: O(n²). Every node is dequeued at most once, and each dequeue scans a row of
nentries. Withn ≤ 1000that is at most 10⁶ cell reads. Reading the input already costs Θ(n²), so this is asymptotically optimal for this representation. - Space: O(n) for the
distarray and the queue (not counting the input matrix).
Edge cases
| Situation | Outcome |
|---|---|
start == end | Returns 0 before BFS begins |
end is a direct neighbor of start | Discovered in the first row scan, returns 1 |
end is in a disconnected component | Queue drains, returns -1 |
start has no edges | Its row is all zeros, nothing enqueued, returns -1 |
n == 1 | start == end == 0, returns 0 immediately |
Reference solution
from collections import deque
from typing import List
def min_hops(conn: List[List[int]], start: int, end: int) -> int:
if start == end:
return 0
n = len(conn)
dist = [-1] * n # -1 means not yet visited
dist[start] = 0
queue = deque([start])
while queue:
node = queue.popleft()
next_dist = dist[node] + 1
# Scanning the full row is required for adjacency-matrix representation.
for neighbor, connected in enumerate(conn[node]):
if connected and dist[neighbor] == -1:
if neighbor == end: # first arrival is guaranteed optimal
return next_dist
dist[neighbor] = next_dist # mark on enqueue, not on dequeue
queue.append(neighbor)
return -1