深度搜索 java,Java-深度优先搜索

I have implemented two algorithms in Java and when testing depth first search it seems to be taking an incredible amount of time when there are 12 nodes, when using A* it completes it in seconds, I was just wondering if this is to be expected or am I doing something wrong? Its running the search in the background now as I type this and has been going for a few minutes.

I wouldnt normally mind but ive got to test up to 500 nodes which could take days at this rate, is this something I should expect or am I doing something wrong?

Thanks!

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

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);

}

}

}

}

}

解决方案

you are not updating chosenRoute correctly; you always add "firstNode" with the same value to your arraylist, I think you should add the visited node.

I will try to check that later

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值