smu*_*shi 1 java algorithm a-star
我整个周末都玩这个.我试图将节点存储在PriorityQueue数据结构中.我的astar函数似乎没有做它应该做的事情.有人介意看看吗?
public void aStar(Node from, Node to) {
PriorityQueue<Node> exploreList = new PriorityQueue<Node>();
ArrayList<Node> visited = new ArrayList<Node>();
ArrayList<Node> successors = new ArrayList<Node>();
Node current = from;
System.out.println(current.getName());
while (current != to) {
successors = current.getConnected();
Collections.sort(successors);
for (Node n : successors) {
if (!visited.contains(n)) {
exploreList.add(n);
}
for (Node n1 : successors) {
if (n.fSum() > n1.fSum()) {
exploreList.remove(n);
exploreList.add(n1);
}
}
}
visited.add(current);
current = exploreList.remove();
System.out.println(current.getName());
}
Run Code Online (Sandbox Code Playgroud)
节点类在这里
public class Node implements Comparable {
private String name;
private int travDist;
private int straightDist;
private ArrayList<Arc> arcs;
/**
* Constructor for a new node
*
* @param n
*/
public Node(String n, int aTravDist, int aStraightDist) {
name = n;
travDist = aTravDist;
straightDist = aStraightDist;
arcs = new ArrayList<Arc>();
}
/**
* Adds a new arc
*
* @param to
* @param c
*/
public void addArc(Node to, int c) {
arcs.add(new Arc(to, c));
}
/**
* Gets the list of connected nodes to this node
*
* @return
*/
public ArrayList<Node> getConnected() {
ArrayList<Node> returnData = new ArrayList<Node>();
for (Arc a : arcs) {
returnData.add(a.getNode());
}
return returnData;
}
@Override
public int compareTo(Object o) {
//return name.compareTo(((Node) o).getName());
Integer sum = ((Node)o).fSum();
return sum.compareTo(fSum());
}
public int fSum () {
return travDist + straightDist;
}
/**
* Gets the name of the Node
*
* @return
*/
public String getName() {
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
你在做什么不是一个合适的A星算法.
Collections.sort(successors);
Run Code Online (Sandbox Code Playgroud)
你不应该这样做.在A star中,你总是考虑所有的继任者.您不必担心订单 - 优先级队列将负责处理.但是,添加此行会增加算法的复杂性.
for (Node n1 : successors) {
if (n.fSum() > n1.fSum()) {
exploreList.remove(n);
exploreList.add(n1);
}
}
Run Code Online (Sandbox Code Playgroud)
这是完全错误的.你在这里做的是:你只添加最接近的所有后继者.这将是一个光束搜索,光束大小为1,而不是一个星星 - 只需将它们全部保留.
| 归档时间: |
|
| 查看次数: |
3971 次 |
| 最近记录: |