Problem solution · Python

Minimum Cost Path with Edge Reversals

Minimum Cost Path with Edge Reversals: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Heap or priority queue
Source
Kamyu LeetCode Solutions
Length
37 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Minimum Cost Path with Edge Reversals, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 37 lines of Python from the credited upstream file minimum-cost-path-with-edge-reversals.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMinimum Cost Path with Edge Reversals · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n + elogn)# Space: O(n + e) import heapq  # dijkstra's algorithmclass Solution(object):    def minCost(self, n, edges):        """        :type n: int        :type edges: List[List[int]]        :rtype: int        """        def dijkstra():            best = [float("inf")]*len(adj)            best[0] = 0            min_heap = [(best[0], 0)]            while min_heap:                curr, u = heapq.heappop(min_heap)                if curr != best[u]:                    continue                if u == len(adj)-1:                    return curr                for v, w in adj[u]:                    if not (best[v] > curr+w):                        continue                    best[v] = curr+w                    heapq.heappush(min_heap, (best[v], v))            return -1         adj = [[] for _ in xrange(n)]        for u, v, w in edges:            adj[u].append((v, w))            adj[v].append((u, 2*w))        return dijkstra() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗