2015-10-06 87 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); 
     } 
    } 
}