Shortest Path Through a Network With Hazardous Nodes
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests BFS on filtered graphs and Dijkstra with lexicographic two-criteria cost to navigate networks while minimizing hazardous-node visits then total hops.
Shortest Path Through a Network With Hazardous Nodes
You are given a network of n stations labeled 0 through n-1. Connectivity is described by a list of lines, where each line is an ordered sequence of stations. Any two stations that appear consecutively in the same line are directly connected (the connection is bidirectional and unweighted).
Some stations are marked hazardous. You must solve two navigation problems on this network.
Part 1 — Hazard-Free Routing
Find the fewest hops to travel from origin to destination while never passing through a hazardous station.
- If
originordestinationis itself hazardous, the query is invalid: return-1. - If no hazard-free path exists, return
-1.
Part 2 — Optimal Routing With Hazards Allowed
You may now travel through hazardous stations. Among all paths from origin to destination, choose one that is best under the following priority:
- Primary: minimize the number of hazardous stations visited along the path (including
originanddestinationif they are hazardous). - Secondary: among all paths tied on criterion 1, minimize the total number of hops.
Return the hazard count and hop count for this optimal path.
Return Format
Return a list of two lists:
[[part1_hops], [part2_hazards, part2_hops]]
part1_hopsis the hazard-free hop count, or-1if Part 1 has no valid answer.part2_hazardsandpart2_hopsare both-1ifdestinationis unreachable even when hazards are permitted.
Input
| Parameter | Type | Description |
|---|---|---|
n | int | Number of stations (labeled 0..n-1) |
lines | List[List[int]] | Each inner list is a sequence of connected stations |
origin | int | Starting station |
destination | int | Target station |
hazardous | List[int] | Stations considered hazardous |
Constraints
1 <= n <= 5000 <= len(lines) <= 200- Each line contains between
1andnstation labels (all in range[0, n-1]) 0 <= origin, destination < noriginmay equaldestination0 <= len(hazardous) <= n- Station labels in
hazardousare all in range[0, n-1]; no duplicates - The same pair of stations may appear as neighbors in more than one line (parallel edges are harmless)
- A line with a single station produces no edges
Examples
Example 1
Input: navigate_hazardous_network(5, [[0, 1, 2], [0, 3, 4, 2]], 0, 2, [1, 3])
Output: [[-1], [1, 2]]
Example 2
Input: navigate_hazardous_network(4, [[0, 1], [1, 2], [2, 3]], 0, 3, [1, 2])
Output: [[-1], [2, 3]]
Example 3
Input: navigate_hazardous_network(3, [[0, 1]], 0, 2, [])
Output: [[-1], [-1, -1]]
Hints
Hint 1
For Part 1, think of it as BFS on a stripped-down graph: simply never enqueue a neighbor that appears in the hazardous set, and reject the query immediately if either endpoint is hazardous.
Hint 2
For Part 2, a single numeric cost won't capture both criteria at once. Consider representing the cost of reaching a node as a tuple (hazards_so_far, hops_so_far) — Python compares tuples lexicographically, which matches the required priority order exactly.
Hint 3
In Part 2, a node can legitimately be reached more than once if a later path finds fewer hazards (or the same hazards in fewer hops). Track the best known cost tuple per node and only expand a state when its cost still matches that best — this is the standard Dijkstra stale-entry check.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Building the Graph
Each line [a, b, c, ...] contributes bidirectional edges a–b, b–c, and so on. Iterating consecutive pairs with zip(line, line[1:]) handles this cleanly. A single-station line produces no pairs, so it adds nothing. Duplicate edges from parallel lines are harmless — they just mean the same neighbor appears twice in the adjacency list, and both BFS and Dijkstra handle that correctly.
Part 1 — BFS on a Filtered Graph
Once either endpoint is flagged as hazardous, no safe path can exist, so return -1 immediately.
Otherwise, run standard BFS but refuse to enqueue any neighbor that appears in the hazard set. This has the same effect as deleting all hazardous nodes from the graph. BFS on an unweighted graph visits nodes in non-decreasing hop order, so the first time the destination is dequeued its recorded distance is the minimum. Time and space are both O(V + E).
Part 2 — Dijkstra With a Two-Component Cost
A plain BFS finds the path with the fewest hops, but that path may pass through many hazardous stations. Minimizing hazards first and hops second is a lexicographic objective, which maps naturally onto cost tuples (hazard_count, hops).
Assign each edge a cost of (1, 1) when the neighbor is hazardous and (0, 1) otherwise. Python compares tuples left-to-right, so the min-heap orders states by fewest hazards first and, on ties, by fewest hops. This is exactly the required priority.
Why Dijkstra is correct here:
- Every edge cost is component-wise non-negative.
- Adding a non-negative tuple never makes a total cost lexicographically smaller.
- Therefore, when a node is popped from the heap with a cost equal to
best[node], no future path can improve it. The first such pop is final — this is the standard Dijkstra invariant.
Stale entries: when a better cost for a node is found after it was already pushed, the old heap entry becomes stale. The check if best[node] != (hazard_count, hops): continue skips those entries without affecting correctness.
Counting endpoints: the origin contributes int(origin in hazard_set) to the starting cost. Each step onto a neighbor adds int(neighbor in hazard_set). So both endpoints are counted when hazardous, which is the behavior the test cases expect.
Edge Cases
origin == destination, neither hazardous: Part 1 =0, Part 2 =[0, 0].origin == destination, hazardous: Part 1 =-1, Part 2 =[1, 0].- Destination unreachable even through hazards: returns
[[-1], [-1, -1]]. - A path with more hops but fewer hazards always wins over a shorter path that is more dangerous — e.g., 5 safe hops beats 2 hops through 1 hazardous station.
Complexity
Let V = n and E = Σ(len(line) − 1) (total edges across all lines).
- Part 1: O(V + E) time, O(V + E) space.
- Part 2: O((V + E) log(V + E)) time (each relaxation pushes at most one heap entry; there are at most E relaxations). O(V + E) space.
Reference Solution
from collections import deque
import heapq
from typing import List
def navigate_hazardous_network(n: int, lines: List[List[int]], origin: int, destination: int, hazardous: List[int]) -> List[List[int]]:
# Build undirected adjacency list from consecutive pairs in each line.
graph = [[] for _ in range(n)]
for line in lines:
for a, b in zip(line, line[1:]):
graph[a].append(b)
graph[b].append(a)
hazard_set = set(hazardous)
# Part 1: BFS restricted to safe (non-hazardous) nodes.
part1 = -1
if origin not in hazard_set and destination not in hazard_set:
dist = [-1] * n
dist[origin] = 0
queue = deque([origin])
while queue:
node = queue.popleft()
if node == destination:
part1 = dist[node]
break
for nb in graph[node]:
if nb not in hazard_set and dist[nb] == -1:
dist[nb] = dist[node] + 1
queue.append(nb)
# Part 2: Dijkstra with lexicographic cost (hazard_count, hops).
# Stepping onto a neighbor contributes (1 if hazardous else 0, 1) to the cost.
start_cost = (int(origin in hazard_set), 0)
best = [None] * n
best[origin] = start_cost
heap = [(start_cost[0], start_cost[1], origin)]
while heap:
hazard_count, hops, node = heapq.heappop(heap)
# Discard stale heap entries.
if best[node] != (hazard_count, hops):
continue
if node == destination:
return [[part1], [hazard_count, hops]]
for nb in graph[node]:
candidate = (hazard_count + int(nb in hazard_set), hops + 1)
if best[nb] is None or candidate < best[nb]:
best[nb] = candidate
heapq.heappush(heap, (candidate[0], candidate[1], nb))
return [[part1], [-1, -1]]