Minimum edges to reverse o make path from source to destination
Pattern: Shortest paths
Following an edge in its direction costs 0; going against it means reversing it, which costs 1. Add both versions to a graph and find the cheapest path with 0-1 BFS: free moves go to the front of a deque, paid moves to the back.
The problem
Given a directed graph with vertices 1 to n, a source and a destination, return the fewest edges to reverse so that a
path from the source to the destination exists, or -1 if no reversals can create one.
Think first
- What does reversing an edge let you do?
- How can both choices be modelled?
- Why is plain BFS not enough?
Hints
Brute force, and why it fails
Dijkstra on the 0/1 graph: O(E log V).
The key insight
With only 0 and 1 weights, a deque keeps vertices in distance order without a heap.
Dry run
7 vertices, edges 1→2, 3→2, 3→4, 7→4, 6→2, 5→6, 7→5; from 1 to 7.
Step 1 of 3
The plan
for u → v: add (v, 0) to u and (u, 1) to v
0-1 BFS: cost-0 moves to the front, cost-1 to the back
Complexity
- Time
O(V + E)- Space
O(V + E)
Each vertex is settled once.
Edge cases
- Source equals destination: 0.
- Disconnected: -1.
- Already a direct path: 0.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int minimumEdgeReversal(int n, int[][] edges, int src, int dst) { // vertices 1..n
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) {
adj.get(e[0]).add(new int[]{e[1], 0}); // along the edge: free
adj.get(e[1]).add(new int[]{e[0], 1}); // against it: one reversal
}
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
Deque<Integer> dq = new ArrayDeque<>(); // 0-1 BFS: free moves go to the front, paid ones to the back
dq.add(src);
while (!dq.isEmpty()) {
int u = dq.pollFirst();
for (int[] e : adj.get(u)) {
if (dist[u] + e[1] < dist[e[0]]) {
dist[e[0]] = dist[u] + e[1];
if (e[1] == 0) dq.addFirst(e[0]); else dq.addLast(e[0]);
}
}
}
return dist[dst] == Integer.MAX_VALUE ? -1 : dist[dst];
}
}C++
class Solution {
public:
int minimumEdgeReversal(int n, vector<vector<int>>& edges, int src, int dst) { // vertices 1..n
vector<vector<pair<int, int>>> adj(n + 1);
for (const vector<int>& e : edges) {
adj[e[0]].push_back(make_pair(e[1], 0)); // along the edge: free
adj[e[1]].push_back(make_pair(e[0], 1)); // against it: one reversal
}
vector<int> dist(n + 1, INT_MAX);
dist[src] = 0;
deque<int> dq; // 0-1 BFS: free moves go to the front, paid ones to the back
dq.push_back(src);
while (!dq.empty()) {
int u = dq.front();
dq.pop_front();
for (const pair<int, int>& e : adj[u]) {
if (dist[u] + e.second < dist[e.first]) {
dist[e.first] = dist[u] + e.second;
if (e.second == 0) dq.push_front(e.first); else dq.push_back(e.first);
}
}
}
return dist[dst] == INT_MAX ? -1 : dist[dst];
}
};Python
from collections import deque
class Solution:
def minimumEdgeReversal(self, n: int, edges: list[list[int]], src: int, dst: int) -> int: # vertices 1..n
adj = [[] for _ in range(n + 1)]
for u, v in edges:
adj[u].append((v, 0)) # along the edge: free
adj[v].append((u, 1)) # against it: one reversal
dist = [float("inf")] * (n + 1)
dist[src] = 0
dq = deque([src]) # 0-1 BFS: free moves go to the front, paid ones to the back
while dq:
u = dq.popleft()
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
if w == 0:
dq.appendleft(v)
else:
dq.append(v)
return -1 if dist[dst] == float("inf") else dist[dst]Common mistakes
- Adding both moves with the same cost.
- Pushing cost-0 moves to the back.