如何使循环函数自动化(x)次/使其递归工作

问题描述 投票:1回答:1

我想从邻接矩阵创建一个距离矩阵(即从函数输入一个邻接矩阵,它计算出每个顶点之间有多少个顶点并在矩阵中输出它)下面的例子。

https://imgur.com/a/0k65tkN

我使用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
1个回答
0
投票

您基本上可以将所有重复的代码放入递归方法中。重要的是,此方法具有必要的参数,以跟踪深度,以及在代码的重复部分之外设置的值(例如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);
    }
}

请原谅功能和参数的非创造性名称。

© www.soinside.com 2019 - 2024. All rights reserved.