Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from source node to destination node.
In above graph there were two paths from node 0 to node 6, 0 -> 1 -> 2 -> 3 -> 6 0 -> 1 -> 5 -> 4 -> 6 But for first path only two edges need to be reversed, so answer will be 2 only.
This problem can be solved assuming a different version of the given graph. In this version we make a reverse edge corresponding to every edge and we assign that a weight 1 and assign a weight 0 to original edge. After this modification above graph looks something like below,
Now we can see that we have modified the graph in such a way that, if we move towards original edge, no cost is incurred, but if we move toward reverse edge 1 cost is added. So if we apply Dijkstra’s shortest path on this modified graph from given source, then that will give us minimum cost to reach from source to destination i.e. minimum edge reversal from source to destination.
Below is the code based on above concept.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count all possible walks from a source to a destination with exactly k edges
- Minimum cost to reverse edges such that there is path between every pair of nodes
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Minimum cost path from source node to destination node via an intermediate node
- Dijkstra's shortest path with minimum edges
- Minimum edges required to add to make Euler Circuit
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Print all paths from a given source to a destination
- Number of Walks from source to destination
- Print all paths from a given source to a destination using BFS
- Find if there is a path of more than k length from a source
- Multi Source Shortest Path in Unweighted Graph
- Shortest path with exactly k edges in a directed and weighted graph
- Minimum steps to reach a destination
- Find the minimum cost to reach destination using a train