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
- 51 lines of Python from the credited upstream file minimum-cost-to-repair-edges-to-traverse-a-graph.py.
- The implementation visibly relies on sequence storage.
- No explicit 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(object):6 def minCost(self, n, edges, k):7 """8 :type n: int9 :type edges: List[List[int]]10 :type k: int11 :rtype: int12 """13 def binary_search(left, right, check):14 while left <= right:15 mid = left+(right-left)216 if check(mid):17 right = mid-118 else:19 left = mid+120 return left21 22 def bfs(x):23 lookup = [False]*len(adj)24 lookup[0] = True25 q = [0]26 d = 027 while q:28 if d == k+1:29 break30 new_q = []31 for u in q:32 if u == n-1:33 return True34 for v, w in adj[u]:35 if w > x or lookup[v]:36 continue37 lookup[v] = True38 new_q.append(v)39 q = new_q40 d += 141 return False42 43 adj = [[] for _ in xrange(n)]44 for u, v, w in edges:45 adj[u].append((v, w))46 adj[v].append((u, w))47 left = min(w for _, _, w in edges)48 right = max(w for _, _, w in edges)49 result = binary_search(left, right, bfs)50 return result if result != right+1 else -151