Approach
Breadth-first search
For Shortest Path with Alternating Colors, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 45 lines of Java from the credited upstream file 1129.java.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1enum Color { INIT, RED, BLUE }2 3class Solution {4 public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {5 int[] ans = new int[n];6 Arrays.fill(ans, -1);7 8 List<Pair<Integer, Color>>[] graph = new List[n];9 10 Queue<Pair<Integer, Color>> q = new ArrayDeque<>(List.of(new Pair<>(0, Color.INIT)));11 Arrays.setAll(graph, i -> new ArrayList<>());12 13 for (int[] edge : redEdges) {14 final int u = edge[0];15 final int v = edge[1];16 graph[u].add(new Pair<>(v, Color.RED));17 }18 19 for (int[] edge : blueEdges) {20 final int u = edge[0];21 final int v = edge[1];22 graph[u].add(new Pair<>(v, Color.BLUE));23 }24 25 for (int step = 0; !q.isEmpty(); ++step)26 for (int sz = q.size(); sz > 0; --sz) {27 final int u = q.peek().getKey();28 Color prevColor = q.poll().getValue();29 ans[u] = ans[u] == -1 ? step : ans[u];30 for (int i = 0; i < graph[u].size(); ++i) {31 Pair<Integer, Color> node = graph[u].get(i);32 final int v = node.getKey();33 Color edgeColor = node.getValue();34 if (v == -1 || edgeColor == prevColor)35 continue;36 q.add(new Pair<>(v, edgeColor));37 38 graph[u].set(i, new Pair<>(-1, edgeColor));39 }40 }41 42 return ans;43 }44}45