统一成本搜索Java实现

时间:2019-01-11 16:55:19

标签: java algorithm search uniform-cost-search

我在Java上实现了“统一成本搜索”,但似乎在某个地方陷入了无限循环,您能否让我知道错误在哪里?预先感谢。 您好,我在Java上实现了“统一成本搜索”,但似乎在某个地方陷入了无限循环,您能否让我知道错误在哪里?预先感谢。

package sdaasd;

import java.util.HashSet;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;


public class Ucs {
    public static  <S> Node<S> search(Problem<S> prob) {
          Node<S> startnode= new Node<S>();
          startnode.state=prob.initialState();
          startnode.pathCost=0;
          startnode.parent=null;
        //System.out.println("Start state:\n"+startnode.state);
        priority<S> prior=new priority<S>();
        prior.queue.add(startnode);
          Set<Node<S>> explored = new HashSet<Node<S>>();
          List<Node<S>> path = new ArrayList<Node<S>>();
          Node<S> goalnode=new Node<S>();
          do{
              path.clear();
                Node<S> current = prior.queue.poll();
                explored.add(current);

               for(Node<S> node=current; node!=null; node=node.parent) { path.add(node);
             }
               if (prob.isGoal(current.state)==true) {
                   goalnode.pathCost=current.pathCost;
                   goalnode.action=current.action;
                   goalnode.state=current.state;
                   System.out.println("state:\n"+goalnode.state);
                   goalnode.parent=current.parent;
                   break;
               }
               for(int i=1; i<prob.actions(current.state).size();i++) {
                   Node<S> child=new Node<S>();
                   child.state=prob.result(current.state, prob.actions(current.state).get(i));
                   child.parent=current;
                   child.action=prob.actions(current.state).get(i);
                   int cost=prob.cost(current.state, prob.actions(current.state).get(i));
                   if(!explored.contains(child) && !prior.queue.contains(child)){
                        child.parent = current;
                       child.pathCost=current.pathCost+cost;
                        prior.queue.add(child);
                    } else if (prior.queue.contains(child)&&(child.pathCost>current.pathCost+cost)) {
                         child.parent=current;
                         child.pathCost = current.pathCost+cost;
                         prior.queue.remove(child);
                         prior.queue.add(child);
               }
               }       


               }while (!prior.queue.isEmpty());
          return goalnode;
    } 

}

0 个答案:

没有答案