Java - 深度优先搜索

时间:2013-01-17 16:40:52

标签: java search depth-first-search

我已经在Java中实现了两种算法,当测试深度优先搜索时,当有12个节点时似乎需要花费大量时间,当使用A *它在几秒内完成时,我只是想知道这是否是预计或我做错了什么?它在后台运行搜索,因为我键入了这个并且已经持续了几分钟。 我通常不介意,但我必须测试多达500个节点,这可能需要几天这个速度,这是我应该期待的还是我做错了什么?

谢谢!


import java.util.*;


@SuppressWarnings({ "rawtypes", "unchecked" })

public class DepthFirstSearch {

    Routes distances;
    static Routes routes;

    int firstNode;
     String result = new String();

    ArrayList firstRoute, bestRoute;
    int nodes = 0;
    int routeCost = 0;
    int bestCost = Integer.MAX_VALUE;

    public DepthFirstSearch(Routes matrix, int firstNode) { //new instance

        distances = matrix;
        this.firstNode = firstNode;
    }


    public void run () { //run algorithm
        long startTime = System.nanoTime();
        firstRoute = new ArrayList();
        firstRoute.add(firstNode);
        bestRoute = new ArrayList();
        nodes++;
        long endTime = System.nanoTime();

        System.out.println("Depth First Search\n");
        search(firstNode, firstRoute);
        System.out.println(result);
        System.out.println("Visited Nodes: "+nodes);
        System.out.println("\nBest solution: "+bestRoute.toString() + "\nCost: "+bestCost);
        System.out.println("\nElapsed Time: "+(endTime-startTime)+" ns\n");
    }


    /**
     * @param from node where we start the search.
     * @param route followed route for arriving to node "from".
     */
    public void search (int from, ArrayList chosenRoute) {

        // we've found a new solution
        if (chosenRoute.size() == distances.getCitiesCount()) {

            chosenRoute.add(firstNode);
            nodes++;

            // update the route's cost
            routeCost += distances.getCost(from, firstNode);

            if (routeCost < bestCost) {
                bestCost = routeCost;
                bestRoute = (ArrayList)chosenRoute.clone();
            }

            result += chosenRoute.toString() + " - Cost: "+routeCost + "\n";

            // update the route's cost (back to the previous value)
            routeCost -= distances.getCost(from, firstNode);
        }
        else {
            for (int to=0; to<distances.getCitiesCount(); to++){
                if (!chosenRoute.contains(to)) {

                    ArrayList increasedRoute = (ArrayList)chosenRoute.clone();
                    increasedRoute.add(to);
                    nodes++;

                    // update the route's cost
                    routeCost += distances.getCost(from, to);

                    search(to, increasedRoute);

                    // update the route's cost (back to the previous value)
                    routeCost -= distances.getCost(from, to);
                }
            }
        }

    }

}

1 个答案:

答案 0 :(得分:1)

您没有正确更新selectedRoute;你总是为你的arraylist添加具有相同值的“firstNode”,我认为你应该添加被访问节点。 我稍后会尝试检查