-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathFloydWarshall.java
More file actions
38 lines (37 loc) · 1.05 KB
/
FloydWarshall.java
File metadata and controls
38 lines (37 loc) · 1.05 KB
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
class Solution
{
public void shortest_distance(int[][] matrix)
{
// Code here
// matrix[i][j] == -1 no path to infinity
int n = matrix.length;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==-1){
matrix[i][j] = 1001; //check the contraints and assign acc.
}
}
}
//O(N^3)
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
matrix[i][j] = Math.min(matrix[i][j] , matrix[i][k] + matrix[k][j]);
}
}
}
//detecting a negative cycle
for(int i=0;i<n;i++){
if(matrix[i][i]<0){
System.out.println("negative cycle detected");
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==1001){
matrix[i][j] = -1; //check the contraints and assign acc.
}
}
}
}
}