Problem overview
The method shortestAlternatingPaths receives n, the number of nodes of a directed graph, and two lists of edges: redEdges and blueEdges. Each edge [a, b] goes from node a to node b. The graph may contain self-edges and parallel edges. The method returns a list answer of length n. For each node x, answer[x] is the length of the shortest path from node 0 to x whose edge colors alternate, red then blue then red and so on, or the other way round. It is -1 if no such path exists.
In the second example, n = 3, redEdges = [[0, 1]] and blueEdges = [[2, 1], [1, 2]]. Node 1 is one red edge from node 0. From node 1, the blue edge leads to node 2, so node 2 is two edges away: red, then blue. The answer is [0, 1, 2]. In the first example there are only red edges, so the path 0, 1, 2 would use two reds in a row. Node 2 can't be reached, and the answer is [0, 1, -1].
Approach: search over (node, last color) states
Shortest paths by number of edges call for breadth-first search (BFS). The alternating rule adds a complication: which edges you may take from a node depends on the color of the edge you used to arrive. Arriving at node 1 by a red edge allows only blue edges next, and arriving by a blue edge allows only red ones. So the same node can be useful in two different ways.
The fix is to make the search state a pair: the node and the color of the last edge. A single visited flag per node would be wrong. Reaching node 1 by red first must not stop the search from also reaching it by blue later, because the continuations differ. The solution keeps one flag per node and arrival color.
The start needs care too. Node 0 has no incoming edge, so its first edge may have either color. The search begins with two states, node 0 as if it had arrived by red and node 0 as if it had arrived by blue. The first state allows blue edges next, and the second allows red edges next, so both first colors are covered.
BFS handles states in order of distance, so the first time any state of node x is reached, the path is the shortest alternating one. That first distance goes into dist[x] and is never changed.
Step by step
- Build the adjacency list.
adj[u]holds two lists: index 0 for the red neighbors ofu, index 1 for the blue ones. Nested comprehensions make fresh lists everywhere. - Add the red edges. For each
u, vinredEdges, appendvtoadj[u][0]. Only this direction is stored, because the edges are directed. - Add the blue edges the same way, into
adj[u][1]. - Prepare the answer.
distis[-1] * n, which is already the right value for unreachable nodes. Setdist[0] = 0. - Prepare the visited flags.
visited[v]is a pair[False, False]: one flag per arrival color. Mark both flags of node 0 as visited. - Seed the queue with two tuples
(node, color, distance):(0, 0, 0)and(0, 1, 0). - Loop while the queue is not empty.
- Take the front state into
u,colorandd. The next edge must have the other color,next_color = 1 - color, which flips 0 to 1 and 1 to 0. - Loop over
adj[u][next_color], the neighbors reachable by an edge of that color. - Skip states already seen: continue only if
not visited[v][next_color]. - Mark the state visited as it is queued. Marking at queueing time prevents the same state from being added twice.
- Record the distance if
dist[v]is still-1: set it tod + 1. BFS reaches nodes by increasing distance, so the first value is the shortest. - Queue the new state
(v, next_color, d + 1). - Return
dist.
The solution in Python
class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
adj = [[[] for _ in range(2)] for _ in range(n)]
for u, v in redEdges:
adj[u][0].append(v)
for u, v in blueEdges:
adj[u][1].append(v)
dist = [-1] * n
dist[0] = 0
visited = [[False, False] for _ in range(n)]
visited[0][0] = visited[0][1] = True
queue = deque([(0, 0, 0), (0, 1, 0)])
while queue:
u, color, d = queue.popleft()
next_color = 1 - color
for v in adj[u][next_color]:
if not visited[v][next_color]:
visited[v][next_color] = True
if dist[v] == -1:
dist[v] = d + 1
queue.append((v, next_color, d + 1))
return dist
The Python details worth a closer look:
- Three levels of lists.
adj[u][color]is a list of neighbors. Every comprehension creates new lists. Writing[[[], []]] * nwould share one inner pair among all nodes, and edges of one node would show up everywhere. - Chained assignment.
visited[0][0] = visited[0][1] = TrueassignsTrueto both targets. It is the same as two separate assignments. - Tuple unpacking.
u, color, d = queue.popleft()splits the three-item tuple into three names. The loopsfor u, v in redEdgesdo the same with each two-item edge. - Colors as numbers. 0 is red and 1 is blue. Using numbers lets
1 - colorflip the color and letsadj[u][next_color]pick the right list without anif. - A
deque.popleft()takes constant time, whilelist.pop(0)would costO(length). - Color of the first edge. The state
(0, 0, 0)means "arrived by red", so its next color is blue. The tuple(0, 1, 0)means the opposite. The two seeds don't claim that a real edge was used.
Complexity
Time: O(n + r + b), where r and b are the numbers of red and blue edges. There are at most 2n states, and each enters the queue once. Processing a state reads one color list of its node, and each color list is read by exactly one of the node's two states, so every edge is looked at at most once. Building the adjacency list is linear as well.
Space: O(n + r + b). The adjacency list stores every edge. The visited flags and the queue take O(n).
Edge cases and common mistakes
- Node 0 itself. Its answer is always 0, whatever the edges are. A self-edge on node 0 never changes that, because
dist[0]is only set when it is-1. - No edges. For
n = 3with empty lists, the result is[0, -1, -1]. - Same pair in both colors. With red
[[0, 1], [1, 2]]and blue[[0, 1], [1, 2]], node 2 is reached by red then blue, so the answer is[0, 1, 2]. - One visited flag per node. It makes the search skip a valid second arrival with the other color, and it can report
-1or a longer path where a shorter one exists. - Seeding only one color. Starting with one state would forbid every path whose first edge has the other color.
- Marking states at dequeue time. Marking when a state is taken from the queue, instead of when it is added, lets the same state be queued many times, which wastes work.
- Overwriting
dist. A later arrival at a node is never shorter, so only the first assignment counts. - Parallel edges and self-edges. They are harmless: the visited flags make repeated arrivals at the same state do nothing.
Testing
n = 3,redEdges = [[0, 1], [1, 2]],blueEdges = []gives[0, 1, -1].n = 3,redEdges = [[0, 1]],blueEdges = [[2, 1], [1, 2]]gives[0, 1, 2].n = 3,redEdges = [[0, 1], [0, 2]],blueEdges = [[1, 0]]gives[0, 1, 1].n = 1,redEdges = [[0, 0]],blueEdges = []gives[0].n = 3,redEdges = [[0, 1], [1, 2]],blueEdges = [[0, 1]]gives[0, 1, 2].
