我想制作数字为0-6的数组,数字均匀分布。为了找到所有可能的解决方案,我想使用Recursion来放置一个可以放在那里的数字并移动到下一个位置。但是当我用Eclipse运行它时。它将经历一次然后回到第一个调用并继续for循环,但不再调用该方法。
import java.util.LinkedList;
public class Search {
int WIDTH = 8;
int HEIGHT = 7;
boolean hasDistroStopped = false;
boolean hasSolveStopped = false;
boolean hasUniqueStopped = false;
public LinkedList<String> fDistro = new LinkedList<String>();
//public LinkedList<String> fSolve = new LinkedList<String>();
//public LinkedList<String> fUnique = new LinkedList<String>();
public static void main(String[] args){
Search a = new Search();
FindDistro findDistro = a.new FindDistro();
//FindSolve findSolve = a.new FindSolve();
//FindUnique findUnique = a.new FindUnique();
findDistro.start();
//findSolve.start();
//findUnique.start();
}
public class FindDistro extends Thread{
long start;
int[] field = new int[WIDTH*HEIGHT];
int[] distro = {0,0,0,0,0,0,0};
public FindDistro(){}
public void run(){
start = System.currentTimeMillis();
findFieldsRecursive(field,distro,0);
synchronized(fDistro){
System.out.println("Found " + fDistro.size() + " fields in " + ((System.currentTimeMillis() - start)/1000) + "s.");
hasDistroStopped = true;
}
}
/**
* This method evenly populates recursively the field with numbers and allows every field to be
* found without the danger of invalid ones.
* @param f The current field
* @param d The current distribution of numbers
* @param pos The current position in the field. Has to be zero to start the recursion properly.
*/
public void findFieldsRecursive(int[] f, int[] d, int pos){
// Test if we finished the field
if (pos == f.length){
String a = "";
for (int i = 0; i < f.length; i++){
a += Integer.toString(f[i]);
}
synchronized(fDistro){
fDistro.add(a);
}
return;
}
//Test for the numbers
for(int i = 0; i < HEIGHT; i++){
if(d[i] != WIDTH){
f[i] = i;
d[i]++;
findFieldsRecursive(f,d,pos + 1);
}
}
}
}