Trains the technique from
LeetCode 1129Shortest Path with Alternating ColorsThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A carrier moves pallets between n depots numbered 0 to n - 1 using two networks. roadLegs[i] = [a, b] is a one-way road leg that can take a pallet from depot a to depot b, and railLegs[j] = [u, v] is a one-way rail leg from depot u to depot v. The same leg may be listed more than once, and a leg may start and end at the same depot.
A pallet starts at depot 0. Its route must change network at every step: a road leg is never followed by another road leg, and a rail leg is never followed by another rail leg. The first leg of a route may be of either kind. A route may pass through the same depot more than once.
For every depot, work out the fewest legs on such a route from depot 0 to that depot, and return those counts in depot order. The count for depot 0 is 0, and a depot with no such route at all is reported as -1.
Example 1
Depot 1 is one road leg away and depot 4 likewise. Depot 3 is reached by the road leg 0 to 1 followed by the rail leg 1 to 3. Depot 2 is reached by road 0 to 4, rail 4 to 1, road 1 to 2, which alternates the whole way. No leg of either network ends at depot 5.
Example 2
The rail leg 0 to 1 gets a pallet to depot 1. Reaching depot 2 would mean taking the rail leg 1 to 2 straight after another rail leg, which the route rule forbids, and there are no road legs to break it up.
Example 3
Every leg here starts and ends at the depot it already sits in, so depot 0 stays at 0 legs and nothing reaches depot 1.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def shortest_alternating_paths(n: int, roadLegs: list[list[int]], railLegs: list[list[int]]) -> list[int]:public int[] shortestAlternatingPaths(int n, int[][] roadLegs, int[][] railLegs)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.