如前所述,我正在使用我的 ArrayDeque 的迭代器边缘,以找到具有最低路径成本节点的图块。这是代码:
public static void UCS(String filename)
{
//a double-ended queue, when used with "addFirst" and "remove", it's a LIFO queue
ArrayDeque<Node> fringe = new ArrayDeque<Node>();
//initial tile set
ArrayList<Tile> tileSet = getTilesFromFile(filename);
//start state has no placed tiles, and all tiles are in the unplaced list
State startState = new State(new ArrayList<Tile>(),tileSet);
//the node that goes with the start state, it has 0 path and step cost, and a null parent
Node root = new Node(startState,0.0,0.0,null);
//the fringe starts with just the root node
fringe.addFirst(root);
//These are for keeping track of the best solution since
//we don't just need /a/ solution, we need the best one
//after generating the whole tree
double bestCost = Double.MAX_VALUE;
State bestSolution = null;
Iterator itr = fringe.iterator();
//we go until there are no nodes left to be expanded
while(!fringe.isEmpty())
{
double lowestCost = Double.MAX_VALUE;
Node lowestCostNode = root;
for (int i = 0; i < fringe.size(); i++)
{
if (((Node) itr.next()).getPathCost() < lowestCost)
{
lowestCost = ((Node) itr.next()).getPathCost();
lowestCostNode = ((Node) itr.next());
}
}
//grab the node at the front of the FIFO queue
Node currNode = lowestCostNode;
fringe.remove(currNode);
//if it is a goal state and the path cost is better than the best
//goal state we've seen so far, it's the new best
if(currNode.getState().isGoal() && currNode.getPathCost() < bestCost)
{
bestCost = currNode.getPathCost();
bestSolution = currNode.getState();
}
//generate all child nodes and put them in the fringe
//at the back of the FIFO queue
ArrayList<Node> childNodes = currNode.expand();
for(Node c : childNodes)
{
fringe.addFirst(c);
}
}
//print the solution along with the cost
//you should also print the number of nodes generated and the amount of time it took
//to perform the search
System.out.println(bestSolution);
System.out.println("Cost of best solution: "+bestCost);
}
我敢肯定,有些逻辑可能仍然不正确,但是当我解决这个问题时,我会弄清楚这一点。也忽略奇怪的评论和类似的东西,其中很多是从 BFS 方法复制粘贴的。我得到的问题是这条线:
lowestCost = ((Node) itr.next()).getPathCost();