algorithm - 递归算法的复杂度

标签 algorithm recursion complexity-theory

我有一个算法,想知道它的复杂度,但是有递归,不知道递归怎么算。我的代码是:

public boolean algorithm(int x, int y) {
    if (x == matrixHeight - 1 && matrix1[x][y] == '0') {
        return true;
    } else if (x == 1 && matrix1[x-1][y] == '0') {
        return true;
    } else if (y == matrixWidth - 1 && matrix2[x][y] == '0') {
        return true;
    } else if (y == 1 && matrix2[x][y-1] == '0') {
        return true;
    }
    if (matrix1[x-1][y] == '0' && tempMatrix[x-1][y] == '-'){
        path.push(new int[]{x-1, y});
        tempMatrix[x-1][y] = '+'
        if (!algorithm(x-1, y)) {
            path.pop();
        } else {
            return true;
        }
    }
    if (matrix2[x][y] == '0' && tempMatrix[x][y+1] == '-'){
        path.push(new int[]{x, y+1});
        tempMatrix[x][y+1] = '+';
        if (!algorithm(x, y+1)) {
            path.pop();
        } else {
            return true;
        }
    }
    if (matrix1[x][y] == '0' && tempMatrix[x+1][y] == '-'){
        path.push(new int[]{x+1, y});
        tempMatrix[x+1][y] = '+';
        if (!algorithm(x+1, y)) {
            path.pop();
        } else {
            return true;
        }
    }
    if (matrix2[x][y-1] == '0' && tempMatrix[x][y-1] == '-'){
        path.push(new int[]{x, y-1});
        tempMatrix[x][y-1] = '+';
        if (!algorithm(x, y-1)) {
            path.pop();
        } else {
            return true;
        }
    }
    return false;
}
  • 在那里,x , y是矩阵中的坐标。
  • matrix1matrix2是包含 '0' 的二维数组或 '1'
  • tempMatrix是一个包含'+'或'-'的二维数组
  • path是一个堆栈
  • matrixHeightmatrix1.length
  • matrixWidthmatrix[0].length
  • N , M是矩阵的大小(常量)

注意:这是使用回溯的迷宫求解器。

最佳答案

对于递归,需要生成递归关系并求解。参见 http://en.wikipedia.org/wiki/Recurrence_relation .没有固定的方法来解决每个递归关系,甚至没有从算法中生成递归关系的方法。

一个例子是归并排序。考虑每次递归调用完成了多少工作。第一,有一个恒定的时间划分;然后进行两次递归调用;然后是线性时间合并。递归调用需要多少工作?好吧,每个人都做同样的事情,两次递归调用加上线性合并步骤。所以你需要一个表达式来表示树的深度和宽度。你知道对于 n 的输入大小,树的高度是 O(log(n)),并且在每一步总共完成 O(n) 合并工作,因此 O(n log(n)) 工作是总计完成。

关于algorithm - 递归算法的复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5748785/

相关文章:

c - C中最多3个硬币的快速硬币找零算法

javascript - 如何使用 JavaScript 将递归 JSON 重新排列为树结构?

algorithm - 在 Mathematica 中迭代生成 Sierpinski 三角形?

algorithm - 如何为更复杂的算法(例如快速排序)计算顺序(大 O)

algorithm - 多维数据分类

algorithm - 查找具有 n-1 个相等分量的向量

c# - 创建大量数字的库或方法

c# - 递归算法后变量神秘地不断变化

c++ - 这个算法的复杂度是多少

Java : Replace a specific char in string to it is index