Reputation: 955
I'm running the following code on a 4x4 array:
private static final int DIMENSION = 4, MAXIMUM = 99;
public static int[][] floydAlgorithm(int[][] oldMatrix)
{
int[][] newMatrix = new int[oldMatrix.length][oldMatrix[0].length];
// nested for loops that update the new matrix with the minimum between the
// old array entry and the sum of two elements along the same row and
//column of the old array entry
for (int x = 0; x < oldMatrix.length; x++)
{
for (int y = 0; y < oldMatrix[0].length; y++)
{
for (int i = 0; i < DIMENSION; i++)
newMatrix[x][y] = Math.min(oldMatrix[x][y],
oldMatrix[x][i] + oldMatrix[i][y]);
}
}
return newMatrix;
}
public static void fillFloydMatrix(int[][] matrix) // fills 2d array with values
{
int [] allInts = {0, 7, 5, MAXIMUM, MAXIMUM, 0, 7, 6,
MAXIMUM, MAXIMUM, 0, MAXIMUM, 4, 1, 11, 0};
for (int x = 0; x < matrix.length; x++)
for (int y = 0; y < matrix[0].length; y++)
matrix[x][y] = allInts[DIMENSION * x + y];
}
public static void displayMatrix(int[][] matrix)
{
for (int x = 0; x < matrix.length; x++)
{
for (int y = 0; y < matrix[0].length; y++)
System.out.print(matrix[x][y] + " ");
System.out.println();
}
}
public static void main(String[] args)
{
int[][] floydMatrix = new int[DIMENSION][DIMENSION];
fillFloydMatrix(floydMatrix);
displayMatrix(floydMatrix);
floydMatrix = floydAlgorithm(floydMatrix);
System.out.println();
displayMatrix(floydMatrix);
}
For some reason, this code outputs the two arrays below, the first of which prints as expected but the second does not:
0, 7, 5, 99
99, 0, 7, 6
99, 99, 0, 99
4, 1, 11, 0
*
0, 7, 5, 99
10, 0, 7, 6
99, 99, 0, 99
4, 1, 11, 0
The 99 on the leftmost column, 2nd row, correctly updates to 10 ([1][3] + [3][0], 6 + 4) but the upper rightmost 99 does not update to 13 ([0][1] + [1][3], 7 + 6) and the 11 at the bottom does not update to 8 ([1][2] + [3][1], 7 + 1). I've tried to find out why but ultimately, I have had no luck in spotting what the issue is. Thus I ask for help in finding the reason why? Thank you so much for your help and time in advance and of course, I will continue to look into why this behavior might be but additional eyes can't hurt.
Upvotes: 0
Views: 48
Reputation: 4623
Change this
newMatrix[x][y] = Math.min(oldMatrix[x][y],
oldMatrix[x][i] + oldMatrix[i][y]);
with this:
newMatrix[x][y] = Math.min(newMatrix[x][y],
oldMatrix[x][i] + oldMatrix[i][y]);
You will also need to initialize your new matrix by filling with Integer.MAX_VALUE. See Arrays.fill .
Upvotes: 1