有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java递归不起作用

我想用数字0-6做一个数组,其中数字均匀分布。为了找到每个可能的解决方案,我想使用递归来放置一个可以放置在那里的数字,然后移动到下一个位置。但是当我用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);
            }
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    递归正在工作:

    enter image description here

    不过,您的算法可能不是。我不太清楚你想实现什么