【问题标题】:How to automate a loop function to work (x) times/make it work recursively如何自动化循环函数工作(x)次/使其递归工作
【发布时间】:2019-09-09 07:32:37
【问题描述】:

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

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】:

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

    请原谅没有创意的函数和参数名称。

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2011-03-18
      • 1970-01-01
      • 2022-01-15
      • 2012-02-24
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多