Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) > Weight(E2) < Weight(E3) …. ). If no such path exists then print -1.
Input: source = 4, destination = 3
4 – 2 – 1 – 3 (Edge Weights: 8, 3, 10) and 4 – 1 – 2 – 3 (Edge Weights: 6, 3, 10) are the only valid paths.
Second path takes the minimum cost i.e. 19.
Input: source = 2, destination = 4
No such path exists.
Approach: Here, We need to keep two copies of adjacent lists one for positive difference and other for negative difference. Take a Priority Queue as in Dijkstras Algorithm and keep four variables at a time i.e.,
- cost: To store the cost of the path till current node.
- stage: An integer variable to tell what element needs to be taken next, if the previous value was negative then a positive value needs to be taken else take negative.
- weight: Weight of the last visited node.
- vertex: Last visited vertex.
For every vertex push the adjacent vertices based on the required condition (value of stage). See the code for better understanding.
Below is the implementation of the above approach:
- Source to destination in 2-D path with fixed sized jumps
- Minimum edges to reverse to make path from a source to a destination
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Multi Source Shortest Path in Unweighted Graph
- Minimum cost path from source node to destination node via an intermediate node
- Find if there is a path of more than k length from a source
- Multistage Graph (Shortest Path)
- Shortest path in a Binary Maze
- Dijkstra’s shortest path algorithm using set in STL
- Shortest Path using Meet In The Middle
- Some interesting shortest path questions | Set 1
- Shortest path in an unweighted graph
- Dijkstra's Shortest Path Algorithm using priority_queue of STL
- Dijkstra's shortest path with minimum edges
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.