[英]How to modularize heuristic in A* (run-time heuristic)
我想使用策略模式對A *實現中的啟發式進行模塊化,但是在分離它時遇到了一些麻煩。 我嘗試通過比較器初始化優先級隊列,該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;
}
});
}
但是我得到:“無法引用用不同方法定義的內部和內部類的非最終變量啟發式方法。”
我正在一個加權完整圖上運行它,並計划使用一種基本的試探法,即朝着開放集中的最近節點移動(我沒有目標節點,只有一組需要訪問的節點)。 當然,要找到開放集中某個節點的權重最小的邊,我需要開放節點的列表/隊列以及當前節點(具有邊列表),因此我將啟發式接口制作如下:
public interface AStarHeuristic {
public int calculate(Node curr, Queue<Node> open);
}
如何分離出heurisitc,以便可以在運行時對Queue進行排序?
這里的問題是,您正在創建一個匿名內部類,並試圖在調用函數中引用一個局部變量(此處為heuristic
)。 為此,Java要求將變量標記為final
。 如果您嘗試將方法更改為
public AStarSearch(Graph g, final AStarHeuristic heuristic) {
// ... Same as before ...
}
問題應該消失了。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.