使用A *查找最短路径

我正在做一个游戏,其中必须将典当押到节点F。2D数组中存储的值表示:

Pawn (starting point): I    
Destination: F

例如,

Node [row=2,col=1]
Node [row=2,col=2]
Node [row=1,col=2]
Node [row=0,col=3]
Node [row=0,col=4]
Node [row=1,col=4]
Node [row=2,col=5]

Search Path without diagonals
     0   1   2   3   4   5   6
0    -   -   *   *   *   -   -
1    -   -   *   B   *   -   -
2    -   I*  *   B   *  *F   -
3    -   -   -   B   -   -   -
4    -   -   -   -   -   -   -
5    -   -   -   -   -   -   -

我的实现的问题在于它一步一步走。我希望能够检测到方向改变的时间并仅添加此动作,我该如何完成?例如,我不想像以前的示例那样一个接一个地访问所有节点,而是:

Node [row=2,col=1] 
Node [row=2,col=2] // Right

Node [row=0,col=2] // Top

Node [row=0,col=4] // Right

Node [row=2,col=4] // Bottom
Node [row=2,col=5] // Right

我该怎么做?

zijire1 回答:使用A *查找最短路径

我没有检查算法的实现,但是tt显示您得到的结果是Node对象的列表。可能看起来像这样:

List<Node> path = aStar.findPath();

那么您要做的就是从结果中排除所有中间节点。您可以在实际算法之后执行此操作(免责声明:未经测试的代码):

List<Node> path = aStar.findPath();
//a path with intermediate nodes removed
List<Node> filteredPath = new ArrayList<>(path.size());
for(int i=0; i<path.size(); i++) {
    Node current = path.get(i);
    //the first and the last element get into the result in any case
    if(i==0 || i==path.size()-1) {
          filteredPath.add(current);
    } else {
          //for the elements in between we are detecting the direction change
          Node previous = path.get(i-1);
          Node next = path.get(i+1);
          //is the step from the previous node to this one vertical
          boolean isPreviousStepVertical = current.getCol()==previous.getCol();
          //is the step from this node to the next one vertical
          boolean isNextStepVertical = current.getCol()==next.getCol();
          //we only add the nodes for which the direction has changed
          if(isPreviousStepVertical!=isNextStepVertical) {
               filteredPath.add(current);
          }

    } 
}

想法是检查每个节点的方向是否实际改变(从垂直方向变为水平方向,反之亦然),并且仅保留必要的节点。

我认为典当不能对角移动,也不能移回已访问的单元。否则,您需要计算节点之间的实际方向矢量,并将其与每个方向进行比较。

更新:要使AStar实现按预期工作,您需要注释掉与addAdjacentUpperRowaddAdjacentLowerRow中对角线移动相对应的四行,例如:

checkNode(currentNode,col - 1,upperRow,getDiagonalCost()); // Comment this if diagonal movements are not allowed

此后,一切都会按预期进行:https://ideone.com/77MAxg

本文链接:https://www.f2er.com/3016960.html

大家都在问