我在尝试生成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));
}
}
}
}
}
答案 0 :(得分: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);
}
}
}