2015-10-06 86 views
0

我在嘗試生成n * n個網格的所有可能組合時遇到了問題。下面的代碼顯示了我將如何使用嵌套循環和2 * 2網格去解決這個問題。但是,如果我想爲6 * 6網格做同樣的事情,那麼製作如此廣泛的循環列表就太煩人了。如何將這些嵌套循環轉換爲遞歸形式?

任何人都可以幫助我將bruteSolve()方法轉換爲遞歸方法,以便我可以選擇網格有多大?

感謝提前:)這一直是我一直停留在爲年齡:(

static ArrayList<Integer> numbers; 

static int n; 

static int [] [] grid; 

static int count; 


public static void main (String [] args){ 

    n = 2; 

    grid = new int [n] [n] ; 

    bruteSolve(n); 
} 

public static void bruteSolve(int n){ 

    for (int i=1; i<n+1; i++){ 
     grid [0][0] = i; 
     for (int j=1; j<n+1; j++){ 
      grid [0][1] = j; 
      for (int k=1; k<n+1; k++){ 
       grid [1][0] = k; 
       for (int l=1; l<n+1; l++){ 
        grid [1][1] = l; 


         System.out.println(Arrays.deepToString(grid)); 


       } 
      } 
     } 
    } 

} 
+2

我想你想看看製作一個自定義對象與方法用於處理問題單循環實例如果該方法接受一個對象作爲輸入,則可以遞歸地使用該對象。 –

回答

0
public static void main (String [] args){ 
    int[][] arr = new int[2][2]; 
    int from = 1, to = 2; // counter range 

    doit(0, arr, from, to); 
    // or 
    doit2(0, 0, arr, from, to); 
} 

// single iterator - process the data as unidimensional array, computing real indexes 
public static void doit(int index, int[][] arr, int from, int to) { 
    if(arr == null || arr.length == 0 || arr[0] == null || arr[0].length == 0) { 
     System.err.println("Matrix inconsistent"); 
     return; 
    } 
    if(index >= arr.length * arr[0].length) { 
     System.out.println(Arrays.deepToString(arr)); 
    } else { 
     int x = index % arr[0].length; 
     int y = index/arr[0].length; 
     for(int n = from;n <= to;n++) { 
      arr[y][x] = n; 
      doit(index+1, arr, from, to); 
     } 
    } 
} 

// less complex but more comparisons 
public static void doit2(int x, int y, int[][] arr, int from, int to) { 
    if(arr == null || arr.length == 0 || arr[0] == null || arr[0].length == 0) { 
     System.err.println("Matrix inconsistent"); 
     return; 
    } 
    if(y >= arr.length) { 
     System.out.println(Arrays.deepToString(arr)); 
    } else if(x >= arr[0].length) { 
     doit2(0, y+1, arr, from, to); 
    } else { 
     for(int n = from;n <= to;n++) { 
      arr[y][x] = n; 
      doit2(x + 1, y, arr, from, to); 
     } 
    } 
}