KatInterview

Fewest Hops from a Start Node While Avoiding Closed Nodes

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbfsgraphshortest-path

Last 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 directed is true, the edge [u, v] can only be used to go from u to v.
  • If directed is false, 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 from source to v.
  • result[v] is -1 if v cannot be reached, which includes the case where v is closed.
  • If source itself is closed, every entry of result is -1, including result[source].
  • Otherwise result[source] is 0.

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] with 0 <= u, v < n.
  • Self-loops and repeated edges may appear; they do not change the answer.
  • blocked may 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.