VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-edges-reverse-make-path-source-destination/

⇱ Minimum edges to reverse to make path from a source to a destination - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum edges to reverse to make path from a source to a destination

Last Updated : 23 Jul, 2025

Given a directed graph with n nodes and m edges. A source node and a destination node are also given, we need to find how many edges we need to reverse in order to make at least 1 path from the source node to the destination node.
Note: In case there is no way then return -1.

Examples:  

👁 Minimum edges to reverse to make path from a source to a destination

Input: n = 7, src = 0, dst = 6
edges[][] = [ [0, 1], [2, 1], [2, 3], [6, 3], [6, 4], [4, 5], [5, 1] ]
Output: 2
Explanation: In above graph there are two paths from node 0 to node 6:
0 -> 1 -> 2 -> 3 -> 6
0 -> 1 -> 5 -> 4 -> 6
For the first path, two edges need to be reversed, and for second path, three edges need to be reversed, thus the minimum edges to be reversed is 2.

Input: n = 4, src = 1, dst = 4
edges[][] = [ [1, 2], [2, 3], [3, 4] ]
Output: 0
Explanation: One path already exists between node 1 to 4: 1 -> 2 -> 3 -> 4. Thus no nodes need to be reversed.

[Naive Approach] - Finding All Paths - Exponential Time and O(n ^ 2) Space

We can use recursion to systematically explore all possible paths in a directed graph, taking into account edge directions and using memoization to optimize the process.

Follow the below given steps:

  1. Build an adjacency list representation of the graph, considering both forward and backward edges.
  2. For each directed edge in the input edges, create a forward edge (+1) from the source to the destination and a backward edge (-1) from the destination to the source.
  3. Initialize an array v to keep track of visited nodes, initialize dp for memoization, and set the starting point for calculating the minimum edge reversals.
  4. Recursive Solver (solve method):
    • It recursively explores the graph while considering forward and backward edges.
    • Base cases: Checks for visited nodes or reaching the destination node.
    • Memoization: Stores and retrieves results to avoid redundant calculations.
    • Exploration: Considers both forward and backward edges, updating the minimum edge reversals required.
    • Backtracking: Marks the current node as unvisited after exploration.
  5. Final Result and Handling Impossible Paths:
    • The method returns the minimum edge reversals from the solve method.
    • If the result is a large negative value, it means no valid path exists, so -1 is returned.
    • Otherwise, it returns the minimum edge reversals needed to reach the destination from the source.

Below is given the implementation:


Output
2

[Expected Approach] - By Creating Reverse Edges - O(m * log(n)) Time and O(n + m) Space

The idea here is to make the graph undirected by adding all edges in the reverse direction. Assign weight zero to all edges that are not reversed and weight 1 to all edges that are reversed. Then, use the Dijkstra algorithm to find the minimum weight path from the starting node to the ending node to get the minimum number of operations.

After adding the reversed edges in the graph, it will look like this:

👁 modified graph

Below is given the implementation:


Output
2

[Optimal Approach] - Using Deque - O(n + m) Time and O(n + m) Space

Instead of a priority queue we can use a dequeue which inserts edges with weight 0 from front and edges with weight 1 (reversed edges) from back so that it is filled in the dequeue in sorted manner.

Follow the below given steps:

  1. Graph Construction:
    • Create an adjacency list from the given directed edges.
    • For each edge (from → to), add:
      • A forward edge (to, 0) (no reversal needed).
      • A backward edge (from, 1) (reversal required).
  2. Initialization:
    • Create a dist vector, setting all distances to INT_MAX.
    • Initialize a deque dq for a modified BFS.
    • Set dist[src] = 0 and add src to dq.
  3. Modified BFS Traversal:
    • While dq is not empty:
      • Dequeue a node node.
      • Iterate through its neighbors (node2, weight).
      • If dist[node] + weight < dist[node2]:
        • Update dist[node2].
        • Push node2 to the front (weight 0) or back (weight 1) of dq.
  4. Result Evaluation:
    • If dist[dst] == INT_MAX, return -1 (no valid path).
    • Otherwise, return dist[dst], the minimum edge reversals required.

Below is given the implementation:


Output
2
Comment
Article Tags: