I have to find the distances in a graph through the multiplication of a 2D array, and I am trying to multiply the array of the graph, it works but the output is not correct. And I don't know where the problem is!
public class Graph {
private int[][] AdjacencyMatrix = {
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 1},
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 0},
{0, 1, 0, 0, 0}};
int size = AdjacencyMatrix.length;
private int[][] distanceMatix = new int[size][size];
public void multiply() {
int sum = 0;
//für alle Zeilen in this matrix
for (int row = 0; row < size; row++) {
//für alle Spalten in other matrix
for (int col = 0; col < size; col++) {
//this matrix -> für alle Zellen in der Zeile
//other matrix -> für alle Zellen in der Spalte
for (int index = 0; index < size; index++) {
if (row == col) {
distanceMatix[row][col] = 0;
} else {
distanceMatix[row][col] +=
AdjacencyMatrix[row][index] *
AdjacencyMatrix[index][col];
}
}
}
}
System.out.println("\n-------- Print DistanceMatrix --------\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(distanceMatix[i][j] + " ");
}
System.out.println();
}
}
}
My Output:
0 0 2 0 1
0 0 0 2 0
2 0 0 0 1
0 2 0 0 0
1 0 1 0 0
The correct ouput is this:
0 1 2 1 2
1 0 1 2 1
2 1 0 1 2
1 2 1 0 3
2 1 2 3 0