I want to find the largest distance between any two vertices of a weighted undirected graph using Floyd-warshall algorithm. For this i have made few changes:
I add negative weights instead of positive.
Then i find out the shortest path.
But it does not give me the correct output. Can someone point out the mistake i am making.
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int testcases=sc.nextInt();
for(int t=0;t<testcases;t++)
{
int nodes=sc.nextInt();
int edges=sc.nextInt();
int[][] dist_mat=new int[nodes][nodes];
for(int i=0;i<nodes;i++)
{
for(int j=0;j<nodes;j++)
{
if(i!=j)
{
dist_mat[i][j]=Integer.MAX_VALUE;
}
}
}
for(int i=0;i<edges;i++)
{
int source=sc.nextInt();
int dest=sc.nextInt();
dist_mat[source-1][dest-1]=-sc.nextInt();
dist_mat[dest-1][source-1]=dist_mat[source-1][dest-1];
}
for(int k=0;k<nodes;k++)
{
for(int i=0;i<nodes;i++)
{
for(int j=0;j<nodes;j++)
{
if(i!=j && j!=k && i!=k && dist_mat[i][j]>dist_mat[i][k]+dist_mat[k][j])
{
if(dist_mat[i][k]<Integer.MAX_VALUE && dist_mat[k][j]<Integer.MAX_VALUE)
dist_mat[i][j]=Integer.min(dist_mat[i][j],dist_mat[i][k]+dist_mat[k][j]);
if(dist_mat[j][k]<Integer.MAX_VALUE && dist_mat[k][i]<Integer.MAX_VALUE)
dist_mat[j][i]=Integer.min(dist_mat[j][i],dist_mat[j][k]+dist_mat[k][i]);
}
}
}
}
}
}
The same input is :-
1[number of test cases]
5 4 [number of nodes,number of edges]
1 2 4 [first node, second node, weight]
3 2 3 [first node, second node, weight]
2 5 2 [first node, second node, weight]
4 1 1 [first node, second node, weight]