查找所有可能的路径算法

时间:2016-02-11 03:54:55

标签: java algorithm path-finding

你好StackOverFlow!我今天在这里发帖是因为我在Java中有一个问题,我试图计算我的角色可能用来移动的pogo stick的所有可能组合。角色使用的是弹簧棍,它们都有距离,由用户输入。

同样,总距离也是通过用户输入给出的,并且可以找到所有可能的路径。我已经在下面显示了我的功能,输出和所需的输出,我似乎无法正常使用。

我一直坚持这个问题,我真的希望有人可以帮助我!

/*
 * First integer in input
 */
int totalDistance;

/*
 * The remaining integers in the input
 */
ArrayList<Integer> pogoSticks = new ArrayList<Integer>();

private void findPaths() {
        ArrayList<ArrayList<Integer>> possibleSticks = new ArrayList<ArrayList<Integer>>();

        for (int i = 0; i < pogoSticks.size(); i++) {

            int pogoStickDistance = pogoSticks.get(i);

            if (pogoStickDistance == totalDistance) {
                if (!possibleSticks.contains(new ArrayList<Integer>(pogoStickDistance))) {
                    ArrayList<Integer> list = new ArrayList<Integer>();
                    list.add(pogoStickDistance);
                    possibleSticks.add(list);
                }
            } else if (pogoStickDistance < totalDistance) {
                int remainingDistance = totalDistance;
                ArrayList<Integer> possibleSubSticks = new ArrayList<Integer>();

                possibleSubSticks.add(pogoStickDistance);
                remainingDistance -= pogoStickDistance;

                for (int j = 0; j < pogoSticks.size(); j++) {

                    int pogoStickDistance1 = pogoSticks.get(j);
                    if (pogoStickDistance1 == remainingDistance) {
                        possibleSubSticks.add(pogoStickDistance1);

                        possibleSticks.add(possibleSubSticks);
                        break;
                    } else if (pogoStickDistance1 < remainingDistance) {
                        possibleSubSticks.add(pogoStickDistance1);
                        remainingDistance -= pogoStickDistance1;
                    }

                    if (j == (pogoSticks.size() - 1) && pogoStickDistance1 != remainingDistance) {
                        j = 0;
                    }
                }
            }

        }

        System.out.println(possibleSticks);
    }

以下是运行上述函数时得到的输出:

Enter input: 5 10 4 1 2
[[4,1], [1,4], [2,1,2]]

请注意,5是距离,而10412是弹簧针的距离行程。

问题在于这些并非所有可能的路径!例如,它缺少[1, 1, 1, 1, 1][2, 2, 1]等路径。

有人可以帮我修改我的功能以包含这些吗?我相信它正在发生,因为一旦我的循环发现第一次出现的pogo stick距离小于剩余距离,它将立即使用该路径并忽略其他可能性。

1 个答案:

答案 0 :(得分:1)

                for(int i = 0;i < pogoSticks.size();i++){
                   //part to calculate small enough 
        int[] temps = new int[pogoSticks.size];
        int temp1 = 0; 
                   for(int j; j< pogoStricks.size();i++){
                   if(pogoSticks.getIndex(j) + k <= totalDisatnce){
        temps[temp1] = pogoSticks.getIndex(j);
        }
    //code to calculate number of paths to get to TotalDistance

这应该完成一半的工作,现在你只需要一种方法来计算所有临时变量的距离。我建议你从TotalDistance中减去每个值,看看加起来的数字是否相等。

相关问题