【发布时间】:2020-11-19 14:49:41
【问题描述】:
我必须通过 2D 数组的乘法在 graph 中找到 distances,并且我正在尝试将图形的数组相乘,它可以工作,但是输出不正确。 而且我不知道问题出在哪里!
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();
}
}
}
我的输出:
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
正确的输出是这样的:
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
【问题讨论】:
标签: java arrays matrix multidimensional-array matrix-multiplication