Problem overview
A directed graph has n vertices, labeled 0 to n - 1. Every edge is red or blue, and the graph may contain self-edges and parallel edges. The method shortestAlternatingPaths receives n, the red edges in redEdges and the blue edges in blueEdges, each as an int[][] of [from, to] pairs. It returns an array answer where answer[x] is the length of the shortest path from vertex 0 to vertex x whose edge colors alternate, red-blue-red-blue or blue-red-blue-red. If no such path exists, the entry is -1.
For n = 3, red edges [[0,1],[1,2]] and no blue edges, vertex 1 is one red edge away. Reaching 2 would need two reds in a row, so the answer is [0, 1, -1]. For red [[0,1]] and blue [[2,1],[1,2]], the path 0 -red-> 1 -blue-> 2 alternates, giving [0, 1, 2].
Approach: BFS over states, not just vertices
Shortest path with unit edge lengths is a job for breadth-first search. The new difficulty is the colors rule: which edges you may take next depends on the color of the edge you just used. Arriving at vertex 5 by a red edge is a different situation from arriving by a blue one, because the first continues along blue edges and the second along red ones.
So the search state is a pair, (vertex, color of the last edge). A plain visited flag per vertex would be wrong: after reaching a vertex by red, a later blue arrival could still lead somewhere new, and skipping it would lose paths. The lesson therefore keeps a visited flag for each vertex and each arrival color, which is 2n flags.
At the start there is no previous edge, so the first edge may be of either color. The search begins with two states for vertex 0, one pretending the last edge was red and one pretending it was blue. From a state, only edges of the opposite color are followed, and each one leads to a new state at distance one more. Because BFS handles states in order of distance, the first time any state of a vertex is reached gives that vertex's shortest alternating distance.
Step by step
- Build the adjacency structure.
adj[i][0]is the list of red neighbors of vertexi, andadj[i][1]is the list of blue ones. Each slot needs its own emptyArrayListfirst. - Fill the red lists by looping over
redEdgesand addinge[1]toadj[e[0]][0]. The graph is directed, so no reverse edge is added. - Fill the blue lists the same way, into
adj[e[0]][1]. - Create
distfilled with-1, then setdist[0]to 0. The value-1is the required answer for unreachable vertices, so unreached entries are already correct. - Create
visited, aboolean[n][2], and mark both colors of vertex 0 as visited. - Create the queue. It holds
int[]states of the form{vertex, color of the last edge, distance}. Offer the two starting states for vertex 0. - Loop until the queue is empty. Each state enters the queue at most once.
- Take the front state and unpack it into
u,colorandd. - Flip the color.
nextColor = 1 - colorturns 0 into 1 and 1 into 0. Loop over the neighborsvinadj[u][nextColor]. - Skip states already seen: continue only if
visited[v][nextColor]is false. - Mark it visited right away, when it is queued and not when it is taken out. That keeps one state from being queued twice.
- Record the distance once. If
dist[v]is still-1, set it tod + 1. Later arrivals atvin the other color are never shorter, so the value is never overwritten. - Queue the new state
{v, nextColor, d + 1}. - Return
dist.
The solution in Java
class Solution {
public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {
List<Integer>[][] adj = new ArrayList[n][2];
for (int i = 0; i < n; i++) {
adj[i][0] = new ArrayList<>();
adj[i][1] = new ArrayList<>();
}
for (int[] e : redEdges) {
adj[e[0]][0].add(e[1]);
}
for (int[] e : blueEdges) {
adj[e[0]][1].add(e[1]);
}
int[] dist = new int[n];
Arrays.fill(dist, -1);
dist[0] = 0;
boolean[][] visited = new boolean[n][2];
visited[0][0] = visited[0][1] = true;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0, 0});
queue.offer(new int[]{0, 1, 0});
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int u = curr[0], color = curr[1], d = curr[2];
int nextColor = 1 - color;
for (int v : adj[u][nextColor]) {
if (!visited[v][nextColor]) {
visited[v][nextColor] = true;
if (dist[v] == -1) {
dist[v] = d + 1;
}
queue.offer(new int[]{v, nextColor, d + 1});
}
}
}
return dist;
}
}
Java details worth a closer look:
- A generic array needs the raw type. Java doesn't allow
new List<Integer>[n][2], so the code creates anArrayList[n][2]and assigns it to aList<Integer>[][]. The compiler reports an unchecked warning, but it works. The slots start asnull, which is why the first loop gives each one its own list. - Several variables in one declaration.
int u = curr[0], color = curr[1], d = curr[2];declares threeints in one statement. Likewise,visited[0][0] = visited[0][1] = true;chains assignments from right to left. - States as arrays. The
int[]of three values is a quick way to carry a tuple through a queue. It is compact, though a small class with named fields is easier to read. QueueandLinkedList.offeradds at the back andpollremoves from the front.ArrayDequewould be an equally good choice.- Unboxing.
for (int v : adj[u][nextColor])readsIntegerobjects from the list as plainintvalues.
Complexity
Let r and b be the numbers of red and blue edges.
Time: O(n + r + b). There are at most 2n states, and each is queued once. When a state is processed, only the edges of one color leaving its vertex are scanned. Each vertex appears in two states, so every edge is scanned at most once. Building the lists costs O(n + r + b).
Space: O(n + r + b). The adjacency lists hold every edge, and the queue, visited and dist are all O(n).
Edge cases and common mistakes
- The start vertex.
dist[0]is always 0, whatever the edges are. A cycle back to 0 can't lower or raise it, because both starting states are already marked visited. - Self-edges. A red edge from 0 to 0 would need a blue edge next. With only red edges, the answer for vertex 0 is still 0.
- Parallel edges. Duplicate edges appear twice in a list. The second copy finds the state already visited and is ignored.
- One flag per vertex. With
n = 5, red[[0,1],[2,3],[1,4]]and blue[[0,2],[3,1]], vertex 1 is first reached by a red edge at distance 1. It is reached again, by a blue edge, at distance 3, through0 -blue-> 2 -red-> 3 -blue-> 1. Only that second arrival can continue along the red edge to vertex 4, so the answer is[0, 1, 1, 2, 4]. A single flag per vertex would block the second arrival and leave vertex 4 at-1. - Marking when taken out of the queue. The same state can then be queued several times before it is processed, wasting work.
- Overwriting
dist[v]. A longer alternating route tovin the other color must not replace a shorter earlier answer, which is why the update only happens while the entry is-1. - Starting with one color only. The first edge may be red or blue. Seeding only one state would miss the paths that start with the other color.
Testing
n = 3, red[[0,1],[1,2]], blue[]gives[0, 1, -1].n = 3, red[[0,1]], blue[[2,1],[1,2]]gives[0, 1, 2].n = 5, red[[0,1],[2,3],[1,4]], blue[[0,2],[3,1]]gives[0, 1, 1, 2, 4].n = 5, red[[0,1],[1,2],[2,3],[3,4]], blue[[1,2],[2,3],[3,4]]gives[0, 1, 2, 3, 4].
