Start learning free

LESSON 567 OF 671 · GRAPHS

Shortest Path with Alternating Colors in Java: BFS on (Vertex, Color)

Practice BFS, O(V+E) Read the full explanation

You get a directed graph with n nodes, numbered 0 to n - 1. Every edge is either red or blue. Each pair [u, v] in redEdges is a red edge from u to v. The pairs in blueEdges are the blue edges.

Return an array answer with one number per node. For each node x, answer[x] is the fewest edges on an alternating path from node 0 to x.

A path is alternating when no two edges in a row have the same color. If no alternating path reaches x, answer[x] is -1. For node 0, the answer is always 0.

An edge can lead from a node back to itself. Two nodes can be joined by more than one edge.

Example 1

Input: n = 5, redEdges = [[0,1],[1,3],[2,4]], blueEdges = [[1,2],[3,4],[0,3]]
Output: [0,1,2,1,3]
Explanation: Node 3 is one blue edge away: 0 → 3.
But 3 → 4 is blue too, so 0 → 3 → 4 doesn't alternate.
The shortest alternating path to node 4 is 0 → 1 → 2 → 4.
Its colors are red, blue, red: 3 edges.

Example 2

Input: n = 4, redEdges = [[0,2],[2,3]], blueEdges = [[3,1]]
Output: [0,-1,1,-1]
Explanation: Node 2 is one red edge away: 0 → 2.
The next edge must be blue, but node 2 has no blue edge out.
So nodes 1 and 3 are never reached. Both get -1.

Example 3

Input: n = 3, redEdges = [[0,2],[2,1]], blueEdges = [[2,2]]
Output: [0,3,1]
Explanation: The blue loop at node 2 lets the color switch.
So node 1 is 3 edges away:
0 → 2 (red),
2 → 2 (blue),
2 → 1 (red).

Constraints

  • 1 to 100 nodes.
  • Up to 400 red edges and up to 400 blue edges.
  • Both ends of every edge are nodes from 0 to n - 1.
STEP 1 OF 17
    Ctrl + Enter to check

    JAVA · GRAPHS

    Shortest Path With Alternating Colors in Java, explained

    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

    1. Build the adjacency structure. adj[i][0] is the list of red neighbors of vertex i, and adj[i][1] is the list of blue ones. Each slot needs its own empty ArrayList first.
    2. Fill the red lists by looping over redEdges and adding e[1] to adj[e[0]][0]. The graph is directed, so no reverse edge is added.
    3. Fill the blue lists the same way, into adj[e[0]][1].
    4. Create dist filled with -1, then set dist[0] to 0. The value -1 is the required answer for unreachable vertices, so unreached entries are already correct.
    5. Create visited, a boolean[n][2], and mark both colors of vertex 0 as visited.
    6. 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.
    7. Loop until the queue is empty. Each state enters the queue at most once.
    8. Take the front state and unpack it into u, color and d.
    9. Flip the color. nextColor = 1 - color turns 0 into 1 and 1 into 0. Loop over the neighbors v in adj[u][nextColor].
    10. Skip states already seen: continue only if visited[v][nextColor] is false.
    11. Mark it visited right away, when it is queued and not when it is taken out. That keeps one state from being queued twice.
    12. Record the distance once. If dist[v] is still -1, set it to d + 1. Later arrivals at v in the other color are never shorter, so the value is never overwritten.
    13. Queue the new state {v, nextColor, d + 1}.
    14. 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 an ArrayList[n][2] and assigns it to a List<Integer>[][]. The compiler reports an unchecked warning, but it works. The slots start as null, 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 three ints 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.
    • Queue and LinkedList. offer adds at the back and poll removes from the front. ArrayDeque would be an equally good choice.
    • Unboxing. for (int v : adj[u][nextColor]) reads Integer objects from the list as plain int values.

    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, through 0 -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 to v in 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].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free