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
- 39 lines of C++ from the credited upstream file 1129.cpp.
- The implementation visibly relies on sequence storage, 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 class Color { kInit, kRed, kBlue };2 3class Solution {4 public:5 vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges,6 vector<vector<int>>& blueEdges) {7 vector<int> ans(n, -1);8 vector<vector<pair<int, Color>>> graph(n); 9 queue<pair<int, Color>> q{{{0, Color::kInit}}}; 10 11 for (const vector<int>& edge : redEdges) {12 const int u = edge[0];13 const int v = edge[1];14 graph[u].emplace_back(v, Color::kRed);15 }16 17 for (const vector<int>& edge : blueEdges) {18 const int u = edge[0];19 const int v = edge[1];20 graph[u].emplace_back(v, Color::kBlue);21 }22 23 for (int step = 0; !q.empty(); ++step)24 for (int sz = q.size(); sz > 0; --sz) {25 const auto [u, prevColor] = q.front();26 q.pop();27 ans[u] = ans[u] == -1 ? step : ans[u];28 for (auto& [v, edgeColor] : graph[u]) {29 if (v == -1 || edgeColor == prevColor)30 continue;31 q.emplace(v, edgeColor);32 v = -1; 33 }34 }35 36 return ans;37 }38};39