Shortest Path with Alternating Colors Problem
Description
LeetCode Problem 1129.
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.
You are given two arrays redEdges and blueEdges where:
redEdges[i] = [a_i, b_i]indicates that there is a directed red edge from nodea_ito nodeb_iin the graph, andblueEdges[j] = [u_j, v_j]indicates that there is a directed blue edge from nodeu_jto nodev_jin the graph.
Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.
Example 1:
Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]
Example 2:
Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
Output: [0,1,-1]
Constraints:
1 <= n <= 1000 <= redEdges.length, blueEdges.length <= 400redEdges[i].length == blueEdges[j].length == 20 <= a_i, b_i, u_j, v_j < n
Solution
Approach: BFS over (Node, Last Color)
Every edge has length 1, so shortest paths come from a BFS. The catch is that a node alone is not enough as the BFS state: what we may do next depends on the color of the edge we arrived by. A node reached by a red edge can only continue along blue edges, and the other way around. So the state is (node, color of the last edge), and each node can be visited twice, once per color.
- Build two adjacency lists, one for red edges and one for blue.
- Node 0 has no incoming edge, so start from both
(0, red)and(0, blue): the first step may use either color. - Process the queue level by level. When a node is taken out for the first time, its answer is the current level. From
(node, c), follow only the edges of the other color, and push each(next, other color)state that has not been seen yet.
Because BFS handles states in order of distance, the first time any state of a node comes out is its shortest alternating path. Nodes never reached keep -1. Self-loops and parallel edges need no special care: the seen set stops them from being explored twice.
Complexity: O(n + r + b) time and space, where r and b are the numbers of red and blue edges.
from collections import deque
class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
graph = [[[] for _ in range(n)] for _ in range(2)] # graph[color][u]: 0 = red, 1 = blue
for u, v in redEdges:
graph[0][u].append(v)
for u, v in blueEdges:
graph[1][u].append(v)
# A state is (node, color of the edge we arrived by); node 0 starts with both colors.
seen = [[False] * 2 for _ in range(n)]
seen[0][0] = seen[0][1] = True
queue = deque([(0, 0), (0, 1)])
answer = [-1] * n
steps = 0
while queue:
for _ in range(len(queue)):
node, color = queue.popleft()
if answer[node] == -1:
answer[node] = steps # BFS reaches each node first by a shortest path
nxt = color ^ 1 # the next edge must have the other color
for v in graph[nxt][node]:
if not seen[v][nxt]:
seen[v][nxt] = True
queue.append((v, nxt))
steps += 1
return answer