Given an undirected graph G, the task is to find the shortest path of even-length, given 1 as Source Node and N as Destination Node. Path length refers to the number of edges present in a path (not the cost of the path).
Input: N = 5, G is given below:
All paths from 1(source node) to 5 (destination node) are:
Cost: 16 Length: 2(even)
Cost: 4 Length: 3(odd)
Cost: 10 Length: 4(even)
The shortest path is 1->2->3->5 with total cost 4, but it has an odd-length path and since we are interested in even-length paths only, the shortest path with even-length is 1->2->3->4->5, with total cost 10.
Input 2: N = 4, G is given below:
There is no path of even-length from 1(source node) to 4(destination node).
Create a new Graph (G’). For each node V in initial graph G, create two new nodes V_even and V_odd.
Here, V_odd will be represented as ((V * 10) + 1) and V_even as ((V * 10) + 2).
For example, if node V = 4 then V_odd = 41 and V_even = 42.
Now, for each edge (U, V) in G, add two new edges in G’, (U_even, V_odd) and (U_odd, V_even). Finally, find the Shortest path from (source_even) node to (destination_even) node using Dijkstra Shortest Path Algorithm.
For Graph given in Input 1(above), G’ can be represented as:
It can observed from the graph G’ that there are only even length paths from (1_even) to (5_even). Thus, the odd-length paths get separated in G’ and the required shortest path can be obtained.
Below is the implementation of the above approach:
Time Complexity: (E * log(V))
- Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Minimum edges to reverse to make path from a source to a destination
- Count all possible walks from a source to a destination with exactly k edges
- Sum of shortest distance on source to destination and back having at least a common vertex
- Print all shortest paths between given source and destination in an undirected graph
- Minimum cost path from source node to destination node via an intermediate node
- Source to destination in 2-D path with fixed sized jumps
- Shortest path with exactly k edges in a directed and weighted graph
- Dijkstra's shortest path with minimum edges
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- Multi Source Shortest Path in Unweighted Graph
- D'Esopo-Pape Algorithm : Single Source Shortest Path
- Single source shortest path between two cities
- Number of Walks from source to destination
- Print all paths from a given source to a destination
- Print all paths from a given source to a destination using BFS
- Count total ways to reach destination from source in an undirected Graph
- Check if a destination is reachable from source with two movements allowed | Set 2
- Ways to Remove Edges from a Complete Graph to make Odd Edges