我想实现一个使用递归方法的搜索算法。执行算法的Java递归
该算法应扩大startnode
到其相邻节点,然后选择具有最小成本的相邻节点,然后将该成本添加到pathcost
(其最初是0),并且至少所选择的成本的节点将变为startnode
和继续搜索再次递归直到找到goalnode
。
下面是我实现这种递归的代码。这不是给我任何错误,但它并没有给我预期的解决方案。 INSTEAD它增加了每个相邻节点的成本(我只需要它添加最小成本节点)。我一直在努力去做,但似乎无法找到任何线索如何去做。
Queue<String> frontierNodes = new PriorityQueue<String>();
Queue<Node1> frontierCosts = new PriorityQueue<Node1>(); // here Node1 is class storing the start, end and cost of the map.
public void Search(Node1[] nodes, String startnode, String goalnode, int size, double pathcost){
for(int i=0; i<size;i++) {
if(startnode.equalsIgnoreCase(nodes[i].getStartNode())) {
frontierNodes.add(nodes[i].getEndNode());
frontierCosts.add(new Node1(nodes[i].getCost()));
System.out.println("Frontier Nodes are " +frontierNodes);
System.out.println("Path cost till now "+pathcost);
// Something should be implemented here to add only the least cost
pathcost += frontierCosts.peek().toCostString();
System.out.println("Path cost till now "+pathcost);
}
}
System.out.println("Expanding node... " +frontierNodes.peek());
//Recursive call
Search(nodes, frontierNodes.poll(), goalnode, nodes.length-(frontierNodes.size()), pathcost);
}
actuallly什么应该是发生在这里,探索的StartNode的所有邻居,对它们进行比较,皮卡最低成本节点,并将它们添加到您的最终排名,这是回答你的问题 但不知何故,这并不看作是一个分cost tour algorithm – Vihar
比较成本的条件检查在哪里?您声明您希望选择最低成本,但我看不到任何比较节点成本的代码。 – MadConan
其实我正在使用优先级队列而不是检查成本,以便我可以poll()/ peek()队列头(这是最便宜的)。这不工作吗? :/ – Dee