Shortest Path with Alternating Colors - Problem
Imagine you're navigating through a city where every street is painted either red or blue, and you must follow a special traffic rule: you can only alternate between red and blue streets!
Given a directed graph with n nodes (labeled 0 to n-1), you have two types of edges:
- Red edges: represented by
redEdges[i] = [from, to] - Blue edges: represented by
blueEdges[i] = [from, to]
Your mission is to find the shortest alternating path from node 0 to every other node. An alternating path means you must switch between red and blue edges at each step.
Goal: Return an array where answer[i] is the shortest path length from node 0 to node i following the alternating color rule, or -1 if impossible.
Input & Output
example_1.py โ Basic Alternating Path
$
Input:
n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
โบ
Output:
[0,1,-1]
๐ก Note:
Node 0 is at distance 0. We can reach node 1 via red edge (distance 1). Node 2 cannot be reached because we need a blue edge from node 1, but none exists.
example_2.py โ Multiple Paths Available
$
Input:
n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
โบ
Output:
[0,-1,-1]
๐ก Note:
Only node 0 is reachable. Node 1 requires alternating colors but we can't reach it from 0 with proper alternation. Node 2 has no incoming edges from reachable nodes.
example_3.py โ Complex Graph with Alternating Paths
$
Input:
n = 3, redEdges = [[0,1]], blueEdges = [[1,2]]
โบ
Output:
[0,1,2]
๐ก Note:
Node 0 at distance 0. Reach node 1 via red edge (distance 1). Then reach node 2 via blue edge from node 1 (distance 2). Perfect alternating pattern: red โ blue.
Constraints
- 1 โค n โค 100
- 0 โค redEdges.length, blueEdges.length โค 400
- redEdges[i].length == blueEdges[i].length == 2
- 0 โค ai, bi, uj, vj < n
- Self-loops and parallel edges are allowed
Visualization
Tap to expand
Understanding the Visualization
1
Start Your Journey
Begin at city center (node 0) with option to take either red or blue street first
2
Follow Alternating Pattern
From each intersection, you can only take streets of opposite color to the one you just used
3
BFS Exploration
Like spreading ripples, explore all reachable intersections level by level
4
Track Shortest Routes
Record the shortest path to each destination following the alternating rule
Key Takeaway
๐ฏ Key Insight: By treating (node, last_edge_color) as our state space, we transform the alternating constraint into a standard shortest path problem that BFS can solve optimally in O(V + E) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code