-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiStage.java
103 lines (99 loc) · 2.1 KB
/
MultiStage.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package Unit_2;
import java.util.*;
public class MultiStage {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.print("Enter number of vertices : ");
int n= sc.nextInt();
int cost[][] = new int[n][n];
System.out.println("Enter the cost matrix : ");
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cost[i][j] = sc.nextInt();
int s[] = new int[n];
int p[] = new int[n];
int temp[] = new int[n];
int i, j;
for(i = 0; i < n; i++)
s[i] = temp[i] = p[i] = 0;
System.out.print("1. Forward Approach 2. Backward Approach\nSelect any one method : ");
int option = sc.nextInt();
switch(option)
{
case 1:
for(i = n - 2; i >= 0; i--)
{
boolean c = true;
for(j = 0; j < n; j++)
{
if(cost[i][j] != 0)
{
if(c)
{
s[i] = s[j] + cost[i][j];
p[i] = j;
c = false;
}
else
{
temp[i] = s[j] + cost[i][j];
if(temp[i] < s[i])
{
s[i] = s[j] + cost[i][j];
p[i] = j;
}
}
}
}
}
System.out.print("Optimal path : ");
i = p[0];
System.out.print("0 --> " + i);
while(i != n - 1)
{
i = p[i];
System.out.print(" -- > " + i);
}
System.out.println("\nShortest Distance = " + s[0]);
break;
case 2:
for(j = 0; j < n; j++)
{
boolean c = true;
for(i = 0; i < n; i++)
{
if(cost[i][j] != 0)
{
if(c)
{
s[j] = s[i] + cost[i][j];
p[j] = i;
c = false;
}
else
{
temp[j] = s[i] + cost[i][j];
if(temp[j] < s[j])
{
s[j] = s[i] + cost[i][j];
p[j] = i;
}
}
}
}
}
System.out.print("Optimal path : ");
i = p[n - 1];
System.out.print((n - 1) + " --> " + i);
while(i != 0)
{
i = p[i];
System.out.print(" -- > " + i);
}
System.out.println("\nDistance = " + s[n - 1]);
break;
}
sc.close();
}
}
}