Minimum Cost of a Path With Special Roads — LeetCode 2662 Python Solution

MediumGraphArrayShortest PathHeap (Priority Queue)
Problem
#2662
Reading time
3 min

The problem

You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY).

Python solution

Python
class Solution:
    def minimumCost(
        self, start: List[int], target: List[int], specialRoads: List[List[int]]
    ) -> int:
        def dist(x1: int, y1: int, x2: int, y2: int) -> int:
            return abs(x1 - x2) + abs(y1 - y2)

        q = [(0, start[0], start[1])]
        vis = set()
        ans = inf
        while q:
            d, x, y = heappop(q)
            if (x, y) in vis:
                continue
            vis.add((x, y))
            ans = min(ans, d + dist(x, y, *target))
            for x1, y1, x2, y2, cost in specialRoads:
                heappush(q, (d + dist(x, y, x1, y1) + cost, x2, y2))
        return ans

Complexity

MeasureComplexity
TimeO(n^2 \times \log n)
SpaceO(n^2) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2662. Minimum Cost of a Path With Special Roads is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2662. Minimum Cost of a Path With Special Roads?
LeetCode 2662. Minimum Cost of a Path With Special Roads is rated Medium on LeetCode.
What is the time complexity of LeetCode 2662. Minimum Cost of a Path With Special Roads?
The Python solution on this page runs in O(n^2 \times \log n).
What is the space complexity of LeetCode 2662. Minimum Cost of a Path With Special Roads?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 2662. Minimum Cost of a Path With Special Roads cover?
LeetCode 2662. Minimum Cost of a Path With Special Roads is tagged Graph, Array, Shortest Path and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview