To solve the Shortest Path with Exactly K Edges problem using dynamic programming approach, we can use a similar approach as the Bellman-Ford algorithm for solving the shortest path problem with negative edge costs, but with a slight modification to keep track of the number of edges used.
We will create a 2D table with the number of rows equal to the total number of vertices in the graph, and the number of columns equal to the maximum value of K allowed. Each element in the table will represent the shortest path from the source vertex to the corresponding destination vertex, using exactly i edges. The base case will be i=0, which represents no edges used and the distance from the source vertex to itself is 0.
For each value of i from 1 to K, we will iterate through all the edges in the graph and update the table by checking if the path using the current edge and the previously computed paths using exactly i-1 edges is shorter than the current shortest path using exactly i edges. If it is, we update the corresponding entry in the table with the new shortest path.
The final answer will be the shortest path from the source vertex to the destination vertex using exactly K edges, which is stored in the (destination, K) entry of the table.
Here is the Java code implementing the above approach:
import java.util.*;
public class ShortestPathKEdges {
static int INF = Integer.MAX_VALUE;
static int[][] dp;
static int shortestPathKEdges(int[][] graph, int src, int dest, int k) {
int V = graph.length;
dp = new int[V][k + 1];
for (int[] row : dp)
Arrays.fill(row, INF);
// Base case
dp[src][0] = 0;
for (int i = 1; i <= k; i++) {
for (int u = 0; u < V; u++) {
for (int v = 0; v < V; v++) {
if (graph[u][v] != 0 && dp[u][i - 1] != INF) {
dp[v][i] = Math.min(dp[v][i], dp[u][i - 1] + graph[u][v]);
}
}
}
}
return dp[dest][k] == INF ? -1 : dp[dest][k];
}
// Example usage
public static void main(String[] args) {
int[][] graph = {{0, 10, 3, 2},
{INF, 0, INF, 7},
{INF, INF, 0, 6},
{INF, INF, INF, 0}};
int src = 0, dest = 3, k = 2;
int res = shortestPathKEdges(graph, src, dest, k);
System.out.println("Shortest path from " + src + " to " + dest + " with " + k + " edges is: " + res);
}
}
In this example, the input graph is represented as a 2D array, where graph[i][j] represents the weight of the edge from vertex i to vertex j, and INF represents the absence of an edge. We then call the ‘shortestPathKEdges‘ function with the source vertex, destination vertex, and the maximum number of edges allowed. The function returns the length of the shortest path from the source to the destination using exactly K edges. If there is no such path, the function returns -1.