java - 为什么我的二维数组乘法的输出不正确?
问题描述
我必须通过二维数组的乘法来找到图中的距离,并且我正在尝试将图形的数组相乘,它可以工作,但输出不正确。而且我不知道问题出在哪里!
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
解决方案
您可以使用通用矩阵乘法方法,这样您就不会感到困惑:
int size = 5;
int[][] matrix = {
{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[][] result = new int[size][size];
for (int row = 0; row < size; row++)
for (int col = 0; col < size; col++)
for (int index = 0; index < size; index++)
result[row][col] += matrix[row][index] * matrix[index][col];
// output
for (int[] res : result) System.out.println(Arrays.toString(res));
//[2, 0, 2, 0, 1]
//[0, 3, 0, 2, 0]
//[2, 0, 2, 0, 1]
//[0, 2, 0, 2, 0]
//[1, 0, 1, 0, 1]
另请参阅:将两个对象矩阵相乘的有效方法