我正在尝试用Java实现A *但是我已经碰到了一堵砖墙,基本上不知道如何从这一点开始。
我目前正在关注Wikipedia的伪代码。
我的节点构造如下:
static class Node {
int col;
int row;
int g;
int h;
int f;
public Node(int col, int row, int g, int h) {
this.col = col;
this.row = row;
this.g = g;
this.h = h;
this.f = g+h;
}
}
重要的是要注意在创建节点时计算f
。
我当前的A *代码,不完整:
public void makeAstar(MapParser parsedMap) {
// create the open list of nodes, initially containing only our starting node
ArrayList<Node> openList = new ArrayList<Node>();
// create the closed list of nodes, initially empty
Map closedMap = new Map(rowSize, columnSize, "Closed map");
// Fill closedMap with 0's
closedMap.buildMapWithValue(0);
// Create neighbourlist
ArrayList<Node> neighbourList = new ArrayList<Node>();
// Some vars
int rowTemp = 0;
int colTemp = 0;
int currentCost = 0;
int tempCost = 0;
//TODO hardcore cost! rowTemp+colTemp
// Initialize with the first node
openList.add(new Node(0,0,9,this.getMapValue(0, 0)));
while(!openList.isEmpty()) {
// Consider the best node, by sorting list according to F
Node.sortByF(openList);
Node currentNode = openList.get(0);
openList.remove(0);
// Stop if reached goal (hardcoded for now)
if(currentNode.getCol() == 4 && currentNode.getRow() == 4) {
System.out.println("Reached goal");
break;
}
// Move current node to the closed list
closedMap.setMapValue(currentNode.getRow(), currentNode.getCol(), 1);
// Get neighbours
rowTemp = currentNode.getRow()-1;
colTemp = currentNode.getCol();
if(!currentNode.isTopRow()) { // Add value ^
neighbourList.add(new Node(rowTemp, colTemp,rowTemp+colTemp,this.getMapValue(rowTemp, colTemp)));
}
rowTemp = currentNode.getRow();
colTemp = currentNode.getCol()-1;
if(!currentNode.isRightColumn()) { // Add value <
neighbourList.add(new Node(rowTemp, colTemp,rowTemp+colTemp,this.getMapValue(rowTemp, colTemp)));
}
rowTemp = currentNode.getRow();
colTemp = currentNode.getCol()+1;
if(currentNode.isLeftColumn()) { // Add value >
neighbourList.add(new Node(rowTemp, colTemp,rowTemp+colTemp,this.getMapValue(rowTemp, colTemp)));
}
rowTemp = currentNode.getRow()+1;
colTemp = currentNode.getCol();
if(currentNode.isBottomColumn()) { // Add value v
neighbourList.add(new Node(rowTemp, colTemp,rowTemp+colTemp,this.getMapValue(rowTemp, colTemp)));
}
// As long as the neighbour list is not empty
while(!neighbourList.isEmpty()) {
Node temp = neighbourList.get(0);
neighbourList.remove(0);
if(!isNotInClosedMap(temp.getRow(), temp.getCol())) {
continue;
}
//Stuck here !
}
}
}
关于最后一行的评论基本上是我已经结束的地方,这相当于伪代码中for each neighbor in neighbor_nodes(current)
附近的东西。此外,我理解G
是起始节点的总成本,但我该如何计算这个值呢?
正如有些人可能会注意到我在初始创建邻居G
时添加了一个硬编码的row+col
值,这就是起始位置为0,0
。
答案 0 :(得分:1)
我认为您正在寻找的计算是:
tentative_g_score := g_score[current] + dist_between(current,neighbor)
这意味着您需要每个节点将分数存储在到目前为止找到的最佳路径上。您有一个当前节点的新分数,目标是如果通过当前节点的路径优于邻居节点的最佳先前分数,则更新其每个邻居的最佳分数。
我不确定您的硬编码G值相对于算法的重要性。如果您已经知道到达每个节点的最佳案例成本,我认为您不需要A *。
我强烈建议重构以重命名字段以匹配您正在使用的伪代码中的标识符。这样可以更容易地看到代码的作用与伪代码无关。它还可以帮助将伪代码交错为注释。