【问题标题】:How to modularize heuristic in A* (run-time heuristic)如何在 A* 中模块化启发式(运行时启发式)
【发布时间】:2013-05-06 03:39:28
【问题描述】:

我想使用strategy pattern 来模块化我的 A* 实现中的启发式,但在分离它时遇到了一些麻烦。我尝试使用Comparator 初始化我的优先级队列,该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);
}

我怎样才能分离出我的启发式以便在运行时对我的队列进行排序?

【问题讨论】:

    标签: java algorithm search


    【解决方案1】:

    这里的问题是您正在创建一个匿名内部类,并试图在调用函数中引用一个局部变量(此处为heuristic)。为此,Java 要求将变量标记为final。如果您尝试将方法更改为

    public AStarSearch(Graph g, final AStarHeuristic heuristic) {
         // ... Same as before ...
    }
    

    问题应该会消失。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2011-12-11
      • 2018-07-23
      • 2010-11-04
      • 1970-01-01
      相关资源
      最近更新 更多