Problem 505631 · medium · Level 05 Advanced Algorithms & Graphs

Alternating Red and Blue Lanes

graphs · BFS · state space · directed graph

A warehouse floor has n stations 0 .. n-1 connected by one-way lanes painted red or blue. red[i] = [u, v] is a red lane from u to v; blue[i] = [u, v] is a blue lane from u to v. A robot leaving station 0 must alternate colours: after a red lane it must take a blue one and vice versa. The first lane may be either colour. Lanes may loop back to their own station and may be repeated.

Return a list steps where steps[i] is the fewest lanes needed to reach station i under this rule, or -1 if it cannot be reached. steps[0] = 0.

Examples

Input:  n = 4, red = [[0,1],[2,3]], blue = [[1,2]]
Output: [0, 1, 2, 3]
Explanation: red 0->1, blue 1->2, red 2->3.

Input:  n = 4, red = [[0,1],[1,3]], blue = [[0,2]]
Output: [0, 1, 1, -1]
Explanation: station 3 can only be reached by two red lanes in a row, which is not allowed.

Input:  n = 4, red = [[0,2],[2,3]], blue = [[2,2]]
Output: [0, -1, 1, 3]
Explanation: red 0->2, blue 2->2, red 2->3.

Constraints

  • 1 <= n <= 5000, 0 <= len(red), len(blue) <= 10**4
  • Target O(V + E) time.

Goals

  • Expand each node into two states, one per last colour used
  • Run BFS on the state graph to get unweighted shortest paths
  • Merge the two states back into one answer per node
Starting Python…