-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiStageGraph.java
74 lines (61 loc) · 2.06 KB
/
MultiStageGraph.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//Solving the multi-stage graph problem
// using dynamic programming
import java.util.Arrays;
public class MultiStageGraph {
public static int[] shortestPath(int[][] costAdjacencyMatrix){
int len = costAdjacencyMatrix.length;
int numVertices = len - 1;
//Shortest path Vertex
int[] path = new int[numVertices];
//Cost for each vertex
int[] cost = new int[len];
//Optimal direction vertex from each vertex
int[] d = new int[len];
//Initializing for (joint) or last vertex in path
cost[numVertices] = 0;
d[numVertices] = numVertices;
//Finding costs array and optimal direction vertex array
for(int i = numVertices - 1; i >= 1; i--){
cost[i] = Integer.MAX_VALUE;
for(int j = i + 1; j <= numVertices; j++){
if(costAdjacencyMatrix[i][j] != 0) {
int min = Math.min(cost[i], costAdjacencyMatrix[i][j] + cost[j]);
if(min < cost[i]){
d[i] = j;
}
cost[i] = min;
}
}
}
//Computing optimal optimalPath
int k = 1;
int l = 1;
path[0] = 1;
while(k < numVertices){
path[l] = d[k];
k= d[k]; l++;
}
return path;
}
public int MinimumDistance(int[][] costAdjacencyMatrix){
int[] optimalPath = shortestPath(costAdjacencyMatrix);
int minDist = 0;
return minDist;
}
public static void main(String[] args){
int[][] am = new int[][]{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 2, 1, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 3, 0, 0 },
{ 0, 0, 0, 0, 0, 6, 7, 0, 0 },
{ 0, 0, 0, 0, 0, 6, 8, 9, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 6 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 4 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 5 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
int[] cost = shortestPath(am);
System.out.println("Shortest path is:");
System.out.println(Arrays.toString(cost));
}
}