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))