Minimum Hops Between Two Tasks in a Dependency Graph
Trees & GraphsAuto-graded · 24 test casesLast updated
Find the fewest directed edges from a start node to a goal node in an acyclic graph, returning 0 for identical nodes and -1 when unreachable; tests BFS on unit-weight graphs.
Minimum Hops in a One-Way Network
A system has n stations numbered 0 through n - 1. Connections between them are one-way: each entry [a, b] in links means you can travel from station a to station b, but not from b back to a. The network contains no cycles and no connection from a station to itself.
You start at station start and want to reach station goal. Return the minimum number of connections you must use to get there.
Function Signature
def min_hops(n: int, links: list[list[int]], start: int, goal: int) -> int:
Rules
- A connection
[a, b]may only be used in the directionatob. - If
start == goal, the answer is0, even if that station has no connections. - If there is no way to reach
goalfromstartfollowing connections in their direction, return-1. - The same connection may appear several times in
links; duplicates do not affect the answer. - Return a single integer.
Constraints
1 <= n <= 10^50 <= len(links) <= 2 * 10^50 <= a, b, start, goal < nfor every[a, b]inlinks- The graph has no directed cycles and no self-loops.
Examples
Example 1
Input: min_hops(6, [[0, 1], [1, 2], [2, 5], [0, 3], [3, 5], [1, 4]], 0, 5)
Output: 2
Example 2
Input: min_hops(6, [[0, 1], [1, 2], [2, 5], [0, 3], [3, 5], [1, 4]], 3, 2)
Output: -1
Example 3
Input: min_hops(3, [[0, 1]], 2, 2)
Output: 0
Hints
Hint 1
Every connection costs exactly one hop, so you are looking for a shortest path in an unweighted graph.
Hint 2
Build an adjacency list that stores only the a -> b direction, then explore outward from start level by level using a queue.
Hint 3
Mark a station as visited when you add it to the queue, record its hop count then, and stop as soon as goal is discovered. Handle start == goal before anything else.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every connection counts as one hop, so this is a shortest-path problem on an unweighted directed graph. Breadth-first search (BFS) from start solves it directly. The acyclic property is not needed for correctness.
- If
start == goal, return0. - Build an adjacency list that records only the forward direction
a -> b. - Keep a
distarray initialised to-1(meaning "not yet discovered"). Setdist[start] = 0and putstartin a queue. - Repeatedly remove a station
xfrom the queue. For each neighbourywithdist[y] == -1, setdist[y] = dist[x] + 1. Ifyis the goal, return that value; otherwise enqueuey. - If the queue empties without discovering the goal, return
-1.
Why it is correct
BFS processes stations in non-decreasing order of hop count. All stations at distance d are dequeued before any at distance d + 1, so a station is first discovered from a station at exactly one hop fewer than its true distance. Hence the value stored on first discovery is the true minimum, and returning immediately when the goal is discovered is safe.
If the goal is never discovered, then it is not in the set of stations reachable by forward edges, so -1 is correct. Only forward edges are stored, so direction is respected. Duplicate links are skipped automatically because the second copy finds the neighbour already discovered.
Complexity
- Time: O(n + m), where
m = len(links). Each station is enqueued at most once and each link is scanned at most once. - Space: O(n + m) for the adjacency list,
dist, and the queue.
The iterative queue also avoids recursion-depth problems on long chains.
Reference solution
from collections import deque
from typing import List
def min_hops(n: int, links: List[List[int]], start: int, goal: int) -> int:
if start == goal:
return 0
adj = [[] for _ in range(n)]
for a, b in links:
adj[a].append(b)
dist = [-1] * n
dist[start] = 0
q = deque([start])
while q:
x = q.popleft()
for y in adj[x]:
if dist[y] < 0:
dist[y] = dist[x] + 1
if y == goal:
return dist[y]
q.append(y)
return -1