Approach
Breadth-first search
For Minimum Cost to Repair Edges to Traverse a Graph, 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
- 61 lines of C++ from the credited upstream file minimum-cost-to-repair-edges-to-traverse-a-graph.cpp.
- The implementation visibly relies on sequence storage.
- 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.
123 45class Solution {6public:7 int minCost(int n, vector<vector<int>>& edges, int k) {8 const auto& binary_search = [](int left, int right, const auto& check) {9 while (left <= right) {10 const auto& mid = left + (right - left) / 2;11 if (check(mid)) {12 right = mid - 1;13 } else {14 left = mid + 1;15 }16 }17 return left;18 };19 20 vector<vector<pair<int, int>>> adj(n);21 const auto& bfs = [&](int x) {22 vector<bool> lookup(n);23 lookup[0] = true;24 vector<int> q = {0};25 for (int d = 0; !empty(q); ++d) {26 if (d == k + 1) {27 break;28 }29 vector<int> new_q;30 for (const auto& u : q) {31 if (u == n - 1) {32 return true;33 }34 for (const auto& [v, w] : adj[u]) {35 if (w > x || lookup[v]) {36 continue;37 }38 lookup[v] = true;39 new_q.emplace_back(v);40 }41 }42 q = move(new_q);43 }44 return false;45 };46 47 for (const auto& e : edges) {48 adj[e[0]].emplace_back(e[1], e[2]);49 adj[e[1]].emplace_back(e[0], e[2]);50 }51 const auto& left = (*min_element(cbegin(edges), cend(edges), [](const auto& a, const auto& b) {52 return a[2] < b[2];53 }))[2];54 const auto& right = (*max_element(cbegin(edges), cend(edges), [](const auto& a, const auto& b) {55 return a[2] < b[2];56 }))[2];57 const auto& result = binary_search(left, right, bfs);58 return result != right + 1 ? result : -1;59 }60};61