【发布时间】:2013-01-17 16:40:52
【问题描述】:
我在 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);
}
}
}
}
}
【问题讨论】:
-
您是否将当前节点标记为已访问?不应该花那么长时间。请在此处发布您的代码。
-
“节点”到底是什么意思?应在几毫秒内搜索到具有 500 个节点的搜索树。或者,如果发现目标极其复杂,您的测试是否会非常复杂?
-
感谢您的回复,我不确定,我不这么认为;我不太清楚我是怎么做的!编辑了原始问题以包含用于 TSP 的代码 @MrSmith42,它运行良好,直到我添加了第 9 个节点,此时它似乎停止/花了很长时间我没有收到最佳路线,正如我所说,这很烦人当我需要测试多达 500 个时。
-
是的,每条路线都会有费用,我需要找到费用最低的路线。
-
当部分解决方案的成本高于已知最便宜的解决方案时,您是否(在搜索树中)剪枝?
标签: java search depth-first-search