I have a code
import java.util.*;
import java.io.*;
public class Dijkstra {
public static int [][] Dijkstra_alg( int n, int e, int mat[][], int s)
{
s=s-1;
int adj[][]=new int[n][n];
for(int i=0;i<e;i++)
{
adj[mat[i][0]-1][mat[i][1]-1]=mat[i][2];
}
// for(int i=0;i<n;i++)
// {
// for(int j=0;j<n;j++)
// {
// System.out.print(adj[i][j]+"\t\t");
// }
// System.out.println();
// }
int dist[][] = new int[n][n]; //dist[][1] holds USP value
Boolean visited[] = new Boolean[n];
for (int i = 0; i < n; i++)
{
dist[i][0] = Integer.MAX_VALUE;
visited[i] = false;
dist[i][1]=1;
}
dist[s][0] = 0;
for (int i = 0; i < n-1; i++)
{
int min = Integer.MAX_VALUE;
int u=-1;
for (int v = 0; v < n; v++)
if (visited[v] == false && dist[v][0] <= min)
{
min = dist[v][0];
u = v;
}
visited[u] = true;
//relax
for (int v = 0; v < n; v++)
{
if (!visited[v] && adj[u][v]!=0 && dist[u][0] != Integer.MAX_VALUE &&dist[u][0]+adj[u][v] < dist[v][0])
{
dist[v][0] = dist[u][0] + adj[u][v];
dist[v][1]=1;
}
else if(!visited[v] && adj[u][v]!=0 && dist[u][0] != Integer.MAX_VALUE &&dist[u][0]+adj[u][v] == dist[v][0])
dist[v][1]=0;
}
}
return dist;
}
public static void main(String args[])
{
int[][] Mat = { {1, 2, 9}, {1, 3, 6}, {1, 4, 5}, {1, 5, 3}, {3, 2, 2}, {3, 4, 4} };
int N = 5;
int E = 6;
int S = 1;
int [][] ans = {{0, 1}, {8, 1}, {6, 1}, {5, 1}, {3, 1}};
int [][] dist=Dijkstra_alg(N,E,Mat,S);
System.out.println(dist.length);
System.out.println(ans.length);
for (int i = 0; i < N; i++)
{
System.out.println(dist[i][0]+"\t\t"+dist[i][1]);
System.out.println(ans[i][0]+"\t\t"+ans[i][1]);
}
System.out.println((Arrays.deepEquals(dist,ans)));
}
}
dist and ans print exactly the same result, but even then, Arrays.deepEquals returns false. Cant figure out why is it displaying false
both these arrays are identical, but giving the result false
the output looks like :
5
5
0 1
0 1
8 1
8 1
6 1
6 1
5 1
5 1
3 1
3 1
false
as you can see the output is exactly identical and shouldn't be giving such an error, but it still does. Cannot figure out why this is happening.
Does anyone know how to fix this?
int dist[][] = new int[n][n];
The second dimension of dist
is n
, while the second dimension of ans
is 2.
Change it to
int dist[][] = new int[n][2];