【问题标题】:How can I convert these nested loops into recursive form?如何将这些嵌套循环转换为递归形式?
【发布时间】:2015-10-07 03:12:41
【问题描述】:

我在尝试生成 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));


                }
            }
        }
    }

}

【问题讨论】:

  • 我想你想看看使用处理单个循环实例的方法制作一个自定义对象。如果该方法接受一个对象作为输入,则可以递归地使用该对象。

标签: java recursion nested-loops


【解决方案1】:
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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-29
    • 2019-04-14
    • 2015-06-25
    • 1970-01-01
    • 2018-05-10
    • 2013-01-04
    • 2016-04-24
    • 2021-12-30
    相关资源
    最近更新 更多