[英]How to modularize heuristic in A* (run-time heuristic)
I was wanting to use the strategy pattern to modularize the heuristic in my A* implementation but am having some trouble separating it. 我想使用策略模式对A *实现中的启发式进行模块化,但是在分离它时遇到了一些麻烦。 I tried to initialize my priority queue with a Comparator
that uses my heuristic in the following way: 我尝试通过比较器初始化优先级队列,该Comparator
通过以下方式使用我的启发式方法:
public AStarSearch(Graph g, AStarHeuristic heuristic) {
this.heuristic = heuristic;
this.open = new PriorityQueue<Node>(10, new Comparator<Node>(){
@Override
public int compare(Node n1, Node n2) {
int fScoreOne = n1.getTotalPathWeight() + heuristic.calculate(n1, open);
int fScoreTwo = n1.getTotalPathWeight() + heuristic.calculate(n1, open);
if (fScoreOne < fScoreTwo)
return 1;
else if (fScoreOne > fScoreTwo)
return -1;
return 0;
}
});
}
But I get: "Cannot refer to non-final variable heuristic inside and inner class defined in a different method." 但是我得到:“无法引用用不同方法定义的内部和内部类的非最终变量启发式方法。”
I am running it on a weighted complete graph with the plan of using a basic heuristic of moving toward the closest node in the open set (I don't have a destination node, just a set of nodes that need to be visited). 我正在一个加权完整图上运行它,并计划使用一种基本的试探法,即朝着开放集中的最近节点移动(我没有目标节点,只有一组需要访问的节点)。 Of course, to find the least weight edge to a node in the open set, I need the list/queue of open nodes and the current node (which has a list of edges), so I made the Heuristic interface as follows: 当然,要找到开放集中某个节点的权重最小的边,我需要开放节点的列表/队列以及当前节点(具有边列表),因此我将启发式接口制作如下:
public interface AStarHeuristic {
public int calculate(Node curr, Queue<Node> open);
}
How can I separate out my heurisitc such that it can be used to sort my Queue at run-time? 如何分离出heurisitc,以便可以在运行时对Queue进行排序?
The issue here is that you are creating an anonymous inner class and are trying to refer to a local variable in the calling function (here, heuristic
). 这里的问题是,您正在创建一个匿名内部类,并试图在调用函数中引用一个局部变量(此处为heuristic
)。 In order to do this, Java requires that the variable be marked final
. 为此,Java要求将变量标记为final
。 If you try changing the method to 如果您尝试将方法更改为
public AStarSearch(Graph g, final AStarHeuristic heuristic) {
// ... Same as before ...
}
the issue should go away. 问题应该消失了。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.