我有一个State类,它包含一个EdgeList的ArrayList。我正在尝试使用DFS计算从一个州到另一个州的路径。
public class State{
private String name;
private ArrayList<State> edges;
public ArrayList<State> depth-first-search(State start, State goal, ArrayList<State> path){
if (start.equals(goal)) {
path.add(start);
return path;
}
else
{
start.setFound(true);
for (State state: start.getEdges())
{
if (!state.found)
{
//we haven't looked at this state, let's look at it
path.add(state);
path = depth-first-search(state, goal, path);
}
}
return path;
}
获取州的路径存在问题,但我不确定究竟是什么。即使在我们找到目标之后,它仍然继续关注州。
答案 0 :(得分:0)
public List<State> dfs(State start, State goal) {
List<State> list = new ArrayList<State>();
if (dfsImpl(start, goal, list))
return list;
else
return null;
}
private boolean dfsImpl(State start, State goal, ArrayList<State> path) {
if (start.equals(goal)){
path.add(start);
return true;
}
else{
start.setFound(true);
for (State state: state.getEdges()){
if (!state.found){
//we haven't looked at this state, let's look at it
path.add(state);
if (DFS(state, goal, path))
return true;
}
}
return false;
}