-
Notifications
You must be signed in to change notification settings - Fork 4
/
CS263_Lab_8.java
75 lines (70 loc) · 2.37 KB
/
CS263_Lab_8.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
// BELLMAN FORD ALGORITHM
import java.util.*;
public class CS263_Lab_8 {
public static void RELAX(int u, int v, int[] distance, int[] precedance, int[][] weight) {
if(distance[v] > (distance[u] + weight[u][v])) {
distance[v] = distance[u] + weight[u][v];
precedance[v] = u;
}
}
public static int NEGATIVE_CYCLE(int u, int v, int[] distance, int[] precedance, int[][] weight) {
RELAX(u, v, distance, precedance, weight);
return 1;
}
public static void PRINT(int[][] array, int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices: ");
int n = sc.nextInt();
int[][] Adjcency_matrix = new int[n][n];
int[][] Weight = new int[n][n];
System.out.println("Enter 1 if edge exist or else zero: ");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
Adjcency_matrix[i][j] = sc.nextInt();
}
}
PRINT(Adjcency_matrix, n);
System.out.println("Enter the weight if edge exist or else zero: ");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
Weight[i][j] = sc.nextInt();
}
}
PRINT(Weight, n);
int[] Distance = new int[n];
for(int i = 0; i < n; i++) {
Distance[i] = 5000;
}
int[] Precedence = new int[n];
for(int i = 0; i < n; i++) {
Precedence[i] = -1;
}
Distance[0] = 0;
int b = 0;
for(int i = 0; i < n - 1; i++) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++) {
if(Adjcency_matrix[j][k] == 1) {
RELAX(j, k, Distance, Precedence, Weight);
b = NEGATIVE_CYCLE(j, k, Distance, Precedence, Weight);
}
}
}
}
if(b == 1) {
System.out.println("Negative cycle is present");
}
for(int i = 0; i < n; i++) {
System.out.print(Distance[i]+" ");
}
System.out.println();
}
}