Fewest Hops from a Start Node While Avoiding Closed Nodes
Trees & GraphsAuto-graded · 21 test casesLast updated
Run a breadth-first search on a directed or undirected graph, skipping closed nodes, to get each node's minimum edge count from the start, or -1 if it cannot be reached.
You are given a graph with n nodes labeled 0 to n - 1. Each edge is a pair [u, v]. A boolean flag tells you whether the edges are directed or undirected.
- If
directedistrue, the edge[u, v]can only be used to go fromutov. - If
directedisfalse, the edge[u, v]can be used in both directions.
Some nodes are closed: they are listed in blocked. A closed node behaves as if it were deleted from the graph together with all of its edges. No path may enter it, leave it, or pass through it.
Every edge has length 1. Starting from node source, find the minimum number of edges on a path to each node, using only nodes that are not closed.
Return a list result of length n where:
result[v]is the minimum number of edges on a valid path fromsourcetov.result[v]is-1ifvcannot be reached, which includes the case wherevis closed.- If
sourceitself is closed, every entry ofresultis-1, includingresult[source]. - Otherwise
result[source]is0.
Constraints
1 <= n, and the graph is small enough to hold in memory as an adjacency list.0 <= source < n.- Every edge is a pair
[u, v]with0 <= u, v < n. - Self-loops and repeated edges may appear; they do not change the answer.
blockedmay be empty and may contain duplicates.- Edges are unweighted, so every edge costs exactly 1.
Examples
Example 1
Input: min_hops_avoiding_closed(5, [[0, 1], [1, 2], [0, 3], [3, 4]], 0, [2], False)
Output: [0, 1, -1, 1, 2]
Example 2
Input: min_hops_avoiding_closed(4, [[0, 1], [1, 2], [2, 3]], 0, [], True)
Output: [0, 1, 2, 3]
Example 3
Input: min_hops_avoiding_closed(6, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]], 2, [1, 4], False)
Output: [-1, -1, 0, 1, -1, -1]
Hints
Hint 1
Every edge costs the same, so the right tool is a breadth-first search rather than anything involving weights or a priority queue.
Hint 2
You do not need to build a new graph. Either skip edges that touch a closed node while building the adjacency list, or refuse to visit a closed node during the search.
Hint 3
Use the distance list itself as the visited marker (-1 means unvisited). Handle a closed source first, then for undirected graphs add each edge in both directions.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because every edge has length 1, a breadth-first search (BFS) from source gives shortest distances.
- Put the closed nodes in a set for constant-time lookup.
- If
sourceis closed, return a list of-1values immediately. - Build an adjacency list, skipping any edge that has a closed endpoint. This is the same as deleting the closed nodes from the graph. For an undirected graph, add each edge in both directions; for a directed graph, add only
u -> v. - Set
dist[source] = 0and run BFS with a queue. When a neighbor still has distance-1, set its distance to the current node's distance plus one and enqueue it.
Why it is correct
BFS visits nodes in non-decreasing order of distance, so the first time a node is discovered it is reached by a shortest path. Dropping every edge that touches a closed node means that no path BFS explores can enter, leave, or cross a closed node. Conversely, every valid path avoiding closed nodes exists in the filtered graph. Closed nodes are never assigned a distance, and nodes reachable only through them are never discovered, so both stay at -1. Using dist as the visited marker and setting it when a node is enqueued ensures each node enters the queue at most once, which also handles self-loops and repeated edges.
Complexity
- Time: O(V + E), since building the adjacency list and the BFS each touch every node and edge a constant number of times.
- Space: O(V + E) for the adjacency list, plus O(V) for the distance list, the closed set, and the queue.
Reference solution
from collections import deque
from typing import List
def min_hops_avoiding_closed(n: int, edges: List[List[int]], source: int, blocked: List[int], directed: bool) -> List[int]:
closed = set(blocked)
dist = [-1] * n
if source in closed:
return dist
adj = [[] for _ in range(n)]
for u, v in edges:
if u in closed or v in closed:
continue
adj[u].append(v)
if not directed:
adj[v].append(u)
dist[source] = 0
queue = deque([source])
while queue:
node = queue.popleft()
for nxt in adj[node]:
if dist[nxt] == -1:
dist[nxt] = dist[node] + 1
queue.append(nxt)
return dist