【发布时间】:2011-04-08 23:52:21
【问题描述】:
我整天都在努力让这个算法启动并运行,但我一辈子都做不到。我在网上阅读了很多教程,以及AS3、javascript和C++的源代码;但我无法将我所看到的内容适应我自己的代码。
我创建了一个 AStar 类,它有一个名为 Node 的嵌套类。地图是一个名为 MAP 的二维数组。
我遇到的最大问题是在寻路函数中拉取 F 值。
我已经实现了 F = G + H,我的问题是实际的 AStar 算法。有人可以帮忙吗,到目前为止我已经走了多远:
import java.util.ArrayList;
public class AStar
{
int MAP[][];
Node startNode, endNode;
public AStar(int MAP[][], int startXNode, int startYNode,
int endXNode, int endYNode)
{
this.MAP = MAP;
startNode = new Node(startXNode, startYNode);
endNode = new Node(endXNode, endYNode);
}
public void pathfinder()
{
ArrayList openList = new ArrayList();
ArrayList closedList = new ArrayList();
}
public int F(Node startNode, Node endNode)
{
return (H(startNode, endNode) + G(startNode));
}
//H or Heuristic part of A* algorithm
public int H(Node startNode, Node endNode)
{
int WEIGHT = 10;
int distance = (Math.abs(startNode.getX() - endNode.getX()) + Math.abs(startNode.getY() - endNode.getY()));
return (distance * WEIGHT);
}
public int G(Node startNode)
{
if(MAP[startNode.getX() - 1][startNode.getY()] != 1)
{
return 10;
}
if(MAP[startNode.getX() + 1][startNode.getY()] != 1)
{
return 10;
}
if(MAP[startNode.getX()][startNode.getY() -1] != 1)
{
return 10;
}
if(MAP[startNode.getX()][startNode.getY() + 1] != 1)
{
return 0;
}
return 0;
}
public class Node
{
private int NodeX;
private int NodeY;
private int gScore;
private int hScore;
private int fScore;
public Node(int NodeX, int NodeY)
{
this.NodeX = NodeX;
this.NodeY = NodeY;
}
public int getX()
{
return NodeX;
}
public int getY()
{
return NodeY;
}
public int getG()
{
return gScore;
}
public void setG(int gScore)
{
this.gScore = gScore;
}
public int getH()
{
return hScore;
}
public void setH(int hScore)
{
this.hScore = hScore;
}
public int getF()
{
return fScore;
}
public void setF(int fScore)
{
this.fScore = fScore;
}
}
}
这是我使用探路者功能所能达到的最远距离:
public void pathfinder()
{
LinkedList<Node> openList = new LinkedList();
LinkedList<Node> closedList = new LinkedList();
Node currentNode;
openList.add(startNode);
while(openList.size() > 0)
{
currentNode = (Node) openList.get(0);
closedList.add(currentNode);
for(int i = 0; i < openList.size(); i++)
{
int cost = F(currentNode, endNode);
}
}
}
【问题讨论】:
-
是的,我一直在努力寻找一个与 Amits 接近的算法来更好地理解它,因为我发现这个算法令人困惑。
-
也许 Google 在该搜索中为您提供了与我不同的结果,因为我看到了三个 java 实现——即完整的实现——以及仅在第一页上的几个带有源代码的教程。我搜索的第二个命中是凯文·希卡鲁·埃文斯(Kevin Hikaru Evans)将您链接到的那个。
标签: java path-finding a-star