MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / shortest_distance

Method shortest_distance

FloydWarshall.java:3–37  ·  view source on GitHub ↗
(int[][] matrix)

Source from the content-addressed store, hash-verified

1class Solution
2{
3 public void shortest_distance(int[][] matrix)
4 {
5 // Code here
6 // matrix[i][j] == -1 no path to infinity
7 int n = matrix.length;
8 for(int i=0;i<n;i++){
9 for(int j=0;j<n;j++){
10 if(matrix[i][j]==-1){
11 matrix[i][j] = 1001; //check the contraints and assign acc.
12 }
13 }
14 }
15 //O(N^3)
16 for(int k=0;k<n;k++){
17 for(int i=0;i<n;i++){
18 for(int j=0;j<n;j++){
19 matrix[i][j] = Math.min(matrix[i][j] , matrix[i][k] + matrix[k][j]);
20 }
21 }
22 }
23 //detecting a negative cycle
24 for(int i=0;i<n;i++){
25 if(matrix[i][i]<0){
26 System.out.println("negative cycle detected");
27 }
28 }
29
30 for(int i=0;i<n;i++){
31 for(int j=0;j<n;j++){
32 if(matrix[i][j]==1001){
33 matrix[i][j] = -1; //check the contraints and assign acc.
34 }
35 }
36 }
37 }
38}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected