我在循环中检查了res(给定操作a的下一个状态)的内容,它们是正确的。它确实会添加到frontier列表中,但值都是相同的,即res的最后一次迭代。
public State BFSearch(){
State initial = new State(array);
LinkedList<State> frontier = new LinkedList<State>();
frontier.add(initial);
while(!frontier.isEmpty()){
State currentState = new State();
currentState = frontier.removeFirst();
if(goalTest(currentState)){
System.out.println("goal");
return currentState;
}
else{
for (Point a : Actions(currentState)) {
State res = new State();
res = Result(currentState,a);
frontier.add(res);
}
}
}
return null;
}发布于 2017-01-27 21:40:48
这在语句currentState = frontier.removeFirst();中非常明显,因为它在while循环中,最终所有元素都会被删除。如果您不想删除,可以尝试peekFirst()方法。
发布于 2017-01-27 21:44:18
我猜您正在尝试实现Breadth-first search。
从您的实现看,您似乎遗漏了这一步:if n is not in S:,因此,只有在您的图形中没有循环的情况下,它才能工作。在其他情况下,您将陷入无限循环。
另外,这段代码中有很多错误:
public State BFSearch(){
State initial = new State(array);
LinkedList<State> frontier = new LinkedList<State>();
frontier.add(initial); <-- initially you have 1 element in list
while(!frontier.isEmpty()){
State currentState = new State(); <-- You don't need to create new instance because you'll overwrite it on next step
currentState = frontier.removeFirst(); <-- you remove initial element
if(goalTest(currentState)){
System.out.println("goal");
return currentState;
}
else{
for (Point a : Actions(currentState)) { <-- I guess Actions is method which returns N points
State res = new State(); <-- You don't need to create instance because you overwrite it on next step
res = Result(currentState,a); <-- is it method with just return state or you just missed `new`
<-- here should be check for existent `res` in `frontier` -->
frontier.add(res); <-- there you put N new steps
}
}
}
return null;
}您的实现可能如下所示:
public State BFSearch() {
State initial = new State(arrays);
List<State> frontier = new LinkedList<>();
frontier.add(initial);
while (!frontier.isEmpty()) {
State currentState = frontier.removeFirst();
if (goalTest(currentState)) {
System.out.println("goal");
return currentState;
} else {
for (Point a : actions(currentState)) {
State res = result(currentState, a);
if (!frontier.contains(res)) {
frontier.add(res);
}
}
}
}
return null;
}重要信息请确保您在State实现中正确实现了equals和hashCode方法
发布于 2017-01-27 21:55:28
很难准确地理解你在做什么或者你的问题是什么,但从我收集的信息来看,你正在删除第一个元素(从一个列表中,这个列表最初可能是一个单一的元素列表),然后你检查它是否与某个条件匹配,如果匹配,则从函数中返回它,如果不匹配,则使用基于另一个集合的元素进行填充。然后重复上述步骤,直到第一个元素是您想要的元素?或者在进入下一次迭代之前打印出列表?
https://stackoverflow.com/questions/41894969
复制相似问题