#2662

Minimum Cost of a Path With Special Roads

Medium
ArrayGraph TheoryHeap (Priority Queue)Shortest PathGraph TraversalDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution treats the problem as a graph where nodes are the start, target, and endpoints of special roads. We use Dijkstra's algorithm to efficiently find the minimum cost path.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph with nodes representing the start, target, and endpoints of special roads.
  2. 2Step 2: Use a priority queue to explore the minimum cost paths from the start node to all other nodes.
  3. 3Step 3: Update costs as shorter paths are found, and stop when the target node is reached.
solution.py30 lines
1# Full working Python code
2import heapq
3
4def minCost(start, target, specialRoads):
5    graph = {}
6    nodes = [tuple(start), tuple(target)]
7    for road in specialRoads:
8        x1, y1, x2, y2, cost = road
9        nodes.append((x1, y1))
10        nodes.append((x2, y2))
11        graph[(x1, y1)] = graph.get((x1, y1), []) + [(cost, (x2, y2))]
12    min_cost = {node: float('inf') for node in nodes}
13    min_cost[tuple(start)] = 0
14    pq = [(0, tuple(start))]
15    while pq:
16        current_cost, current_node = heapq.heappop(pq)
17        if current_node == tuple(target):
18            return current_cost
19        for next_cost, neighbor in graph.get(current_node, []):
20            total_cost = current_cost + next_cost
21            if total_cost < min_cost[neighbor]:
22                min_cost[neighbor] = total_cost
23                heapq.heappush(pq, (total_cost, neighbor))
24        direct_cost = abs(current_node[0] - target[0]) + abs(current_node[1] - target[1])
25        total_cost = current_cost + direct_cost
26        if total_cost < min_cost[tuple(target)]:
27            min_cost[tuple(target)] = total_cost
28            heapq.heappush(pq, (total_cost, tuple(target)))
29    return min_cost[tuple(target)]
30

Complexity note: This complexity is due to the priority queue operations and the number of nodes processed, where n is the number of unique positions considered.

  • 1Using special roads can significantly reduce travel costs if chosen wisely.
  • 2Direct paths may sometimes be the best option, especially when special roads are not advantageous.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.