2016-04-22 95 views
0

我試圖使用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; 
    } 

} 
+0

遞歸在哪裏? –

+0

方法checkElements() –

回答

1

這可能是更容易,如果你改變了遞歸調用

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)。

雖然這似乎很容易計算,但線性遞歸深度通常不是一個好主意(除了識別和支持尾遞歸的語言之外),因爲堆棧大小通常比堆空間更有限 - 您可能很容易遇到堆棧溢出異常。

因此,通常情況下,只有兩個嵌套循環(用於行和列),除非我錯過了重要的東西。代碼中正在進行的處理。

+0

我怎樣才能找到相同的代碼的下界或大的theta? –

+0

我認爲它是完全相同的界限 - 似乎沒有任何會縮短運行時間的特殊輸入 - 在任何情況下,所有單元格似乎都會被遍歷。 –