[英]Finding time complexity of recursive function
我正在尝试使用Big-Oh表示法查找该函数的整体时间复杂度,该函数checkElements()递归调用,该函数驻留在percolates()内部。
public static boolean percolates(boolean[][] open) {
size = open.length;
uf = new WeightedQuickUnionUF((size * size) + 2);
for (int i = 0; i < open.length; i++) {//connect all top row elements to virtual top node.
uf.union(0, i);
}
for (int j = 0; j < open.length; j++) {//connect all bottom row elements to bottom virtual node
uf.union((size * size) + 1, (size * size) - j);
}
int row = 0; // current row of grid
int column = 0;// current column of grid
int ufid = 1; // current id of union find array
checkElements(column, row, open, ufid);
boolean systemPerculates = uf.connected(0, (size * size) + 1);
System.out.println("Does the system percoloates :" + systemPerculates);
return systemPerculates;
}
//search elements in the grid
public static void checkElements(int column, int row, boolean open[][], int ufid) {
if (open[row][column]) {
if (column - 1 >= 0 && open[row][column - 1]) { //check adjacent left
uf.union(ufid, ufid - 1);
}
if (column + 1 < size && open[row][column + 1]) {//check adjacent right
uf.union(ufid, ufid + 1);
}
if (row - 1 >= 0 && open[row - 1][column]) {//check adjacent top
uf.union(ufid, ufid - size);
}
if (row + 1 < size && open[row + 1][column]) {//check adjacent bottom
uf.union(ufid, ufid + size);
}
}
if (column + 1 < size) { //go to next column
ufid++;
column++;
checkElements(column, row, open, ufid);
} else if (column + 1 == size && row + 1 < open.length) { //go to next row
ufid++;
row++;
column = 0;
checkElements(column, row, open, ufid);
} else {
return;
}
}
如果将递归调用更改为
if (column + 1 < size) { //go to next column
checkElements(column + 1, row, open, ufid + 1);
} else if (column + 1 == size && row + 1 < open.length) { //go to next row
checkElements(0, row + 1, open, ufid + 1);
} else {
return;
}
您最多只能在checkElements
进行一次递归调用,并且每个调用似乎都将考虑的输入减少一,并且您在每一步仅进行恒定数量的处理,因此运行时应为O(n)。
尽管这似乎很容易计算,但是线性递归深度通常不是一个好主意(除了在识别和支持尾递归的语言中),因为堆栈大小通常比堆空间要受限制-您可能很容易碰到堆栈溢出异常。
因此,通常情况下,除非我错过了一些重要的问题,否则通常只有两个嵌套循环(用于行和列)。 代码中正在进行的处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.