我正在使用 C# 做关于传教士和食人族的项目。我使用了两种搜索算法,即广度优先搜索和深度优先搜索。使用广度优先搜索,程序从根开始查找第 12 层的结果。但是使用深度优先搜索,它找不到解决方案,这会挂起我的电脑。我认为它在图中进入了一个循环。所以我的问题是,我不能使用深度优先搜索来解决传教士和食人族问题吗?
广度优先搜索的代码是
public State getSolutionStatesBFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, true);
while (searchAgenda.Count > 0) {
CurState = (State)searchAgenda.Dequeue();
if (CurState.Equals(EndState)) {
break;
} else {
if (!isVisited(CurState, visited))
{
generateSucessors(CurState, true);
visited.Add(CurState);
}
}
}
return CurState;
}
深度优先搜索的代码是
public State getSolutionStatesDFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, false);
while (searchAgendaS.Count > 0)
{
CurState = (State)searchAgendaS.Pop();
if (CurState.Equals(EndState))
{
break;
}
else
{
if(!isVisited(CurState,visited))
{
generateSucessors(CurState, false);
}
}
}
return CurState;
}