[英]How to automate a loop function to work (x) times/make it work recursively
我想從一個鄰接矩陣創建一個距離矩陣(例如,從一個函數輸入一個鄰接矩陣,它計算出每個頂點之間有多少個頂點並以矩陣的形式輸出)下面的示例。
我使用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)
您基本上可以將所有重復的代碼放入遞歸方法中。 重要的是,此方法必須具有必要的參數,以跟蹤深度以及在代碼重復部分之外設置的值(例如i
)。
static void recursiveFunction(int distance, int matrix[][], int size, int row, int prevRow, int depth) {
for (int i = 0; i < size; i++) {
if ((adjMatrix[prevRow][i] == 1) && (matrix[row][i] > depth || matrix[row][i] == 0)
&& row != i) {
matrix[row][i] = depth;
if (depth < distance) {
recursiveFunction(distance, matrix, size , row, i, depth +1);
}
}
}
}
static void distanceMatrix(int distance, int result[][], int size) {
for (int i = 0; i < size; i++) {
recursiveFunction(distance, result, size, i, i, 1);
}
}
請為函數和參數使用非創造性的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.