【发布时间】:2019-09-09 07:32:37
【问题描述】:
我想从一个邻接矩阵创建一个距离矩阵(即,从一个函数输入一个邻接矩阵,它会计算出每个顶点之间有多少个顶点并将其输出到一个矩阵中)下面的示例。
我使用 for 循环解决了这个问题。该程序可以生成正确的矩阵,但是,它最多只能在距离为 3 的情况下这样做。我的 for 循环遵循一种模式。如何在不复制 1000 次的情况下将这个过程复制多少次?
The basic premise is: if [i][j]=1 and [j][k]=1 then [i][k]=2
有更好的方法吗?
static void distanceMatrix(int distance, int result[][], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (adjMatrix[i][j] == 1 && (result[i][k] > 1 || result[i][k] == 0) && distance >= 1 && i != k) {
result[i][j] = 1;
for (int k = 0; k < size; k++) {
if ((adjMatrix[j][k] == 1) && (result[i][k] > 2 || result[i][k] == 0) && distance >= 2
&& i != k) {
result[i][k] = 2;
for (int l = 0; l < size; l++) {
if ((adjMatrix[k][l] == 1) && (result[i][l] > 3 || result[i][l] == 0) && distance >= 3
&& i != l) {
result[i][l] = 3;
}
}
}
}
}
}
}
}
For reference, the parameter inputs are as below:
distance: the maximum distance that should be calculated (ie. if input is 2, then only distances of 0,1,2 are calculated)
result[][]: the empty matrix for the distance matrix to be put into
size: the number of total vertices (matrix will be size x size)
【问题讨论】:
标签: java loops recursion matrix adjacency-matrix