![]() |
VOOZH | about |
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 destinationInput: 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.
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:
edges, create a forward edge (+1) from the source to the destination and a backward edge (-1) from the destination to the source.v to keep track of visited nodes, initialize dp for memoization, and set the starting point for calculating the minimum edge reversals.solve method):solve method.Below is given the implementation:
2
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:
Below is given the implementation:
2
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:
(from → to), add: (to, 0) (no reversal needed).(from, 1) (reversal required).dist vector, setting all distances to INT_MAX.dq for a modified BFS.dist[src] = 0 and add src to dq.dq is not empty: node.(node2, weight).dist[node] + weight < dist[node2]: dist[node2].node2 to the front (weight 0) or back (weight 1) of dq.dist[dst] == INT_MAX, return -1 (no valid path).dist[dst], the minimum edge reversals required.Below is given the implementation:
2