Minimum Cost Path with Edge Reversals Problem
Description
LeetCode Problem 3650.
You are given a directed, weighted graph with n nodes labeled from 0 to n - 1, and an array edges where edges[i] = [u_i, v_i, w_i] represents a directed edge from node u_i to node v_i with cost w_i.
Each node u_i has a switch that can be used at most once: when you arrive at u_i and have not yet used its switch, you may activate it on one of its incoming edges v_i → u_i reverse that edge to u_i → v_i and immediately traverse it.
The reversal is only valid for that single move, and using a reversed edge costs 2 * w_i.
Return the minimum total cost to travel from node 0 to node n - 1. If it is not possible, return -1.
Example 1:
Input: n = 4, edges = [[0,1,3],[3,1,1],[2,3,4],[0,2,2]]
Output: 5
Explanation:

- Use the path 0 → 1 (cost 3).
- At node 1 reverse the original edge 3 → 1 into 1 → 3 and traverse it at cost 2 * 1 = 2.
- Total cost is 3 + 2 = 5.
Example 2:
Input: n = 4, edges = [[0,2,1],[2,1,1],[1,3,1],[2,3,3]]
Output: 3
Explanation:
- No reversal is needed. Take the path 0 → 2 (cost 1), then 2 → 1 (cost 1), then 1 → 3 (cost 1).
- Total cost is 1 + 1 + 1 = 3.
Constraints:
2 <= n <= 5 * 10^41 <= edges.length <= 10^5edges[i] = [u_i, v_i, w_i]0 <= u_i, v_i <= n - 11 <= w_i <= 1000
Solution
Approach: Dijkstra's Algorithm
Turn the rule into an ordinary weighted graph. Each edge u -> v with weight w gives two moves: from u to v at cost w, and (by reversing the edge) from v to u at cost 2w. Every reversal is used on the path's own step, so the costs just add up, and the shortest path from node 0 to node n - 1 in this graph is the answer.
Run Dijkstra with a min-heap of (distance, node). Pop the closest node; skip it if its distance is stale; if it is n - 1, return the distance; otherwise relax its neighbours. If the heap runs out first, n - 1 is unreachable and the answer is -1.
Complexity: O((n + m) log m) time and O(n + m) extra space, where m is the number of edges.
from heapq import heappop, heappush
from math import inf
class Solution:
def minCost(self, n: int, edges: List[List[int]]) -> int:
g = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w * 2))
pq = [(0, 0)]
dist = [inf] * n
dist[0] = 0
while pq:
d, u = heappop(pq)
if d > dist[u]:
continue
if u == n - 1:
return d
for v, w in g[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heappush(pq, (nd, v))
return -1