我做了一个简单的迷宫搜索算法,盲目地进入细胞的每个方向 检查目标是否已找到。它可以找到目标,但解决方案仍然很糟糕,因为它在找到目标时不会终止其他递归调用 并且它绘制了它已经走过的所有路径,而不仅是通往目标的一条可能路径。我怎么能改善这个?
伪代码中的基本算法是这样的:
function searchMaze(start_point, end_point, maze) {
// If current point is goal I would like to abort other recursive calls
if(start_point.equals(end_point)) {
pathFound = true;
drawPathInArray();
return;
}
else {
// if current point is not inside the array
if(start_point_not_within_array)
return
else {
// if current point is a wall or a cell that has already been visited
if(cell_is_wall || cell_is_visited)
return;
else {
// mark cell as possible path
markCellInPathArray("#");
setCellVisited();
searchMaze(left_from_start_point, end_point, maze);
searchMaze(right_from_start_point, end_point, maze);
searchMaze(above_start_point, end_point, maze);
searchMaze(below_start_point, end_point, maze);
}
}
}
}
答案 0 :(得分:1)
让函数返回一个布尔值。每当您找到目标的路径时,返回true,否则返回false。一旦从一个递归调用中获得返回值true,就返回。
所涉及的更改将是适当的返回语句,并将您的4个递归调用更改为:
if (searchMaze(left_from_start_point, end_point, maze))
return true;
if (searchMaze(right_from_start_point, end_point, maze))
return true;
if (searchMaze(above_start_point, end_point, maze))
return true;
if (searchMaze(below_start_point, end_point, maze))
return true;
另外,你最后不应该有setCellNotVisited()
吗?
注意:我看到你已经有一个pathFound
变量(可能是一个类变量)。在这种情况下,Marco的解决方案可能更受欢迎,但最好将其更改为返回值。
答案 1 :(得分:1)
您应该将标志添加到每个递归调用中:
pathFound = pathFound || searchMaze(left_from_start_point, end_point, maze);
pathFound = pathFound || searchMaze(right_from_start_point, end_point, maze);
pathFound = pathFound || searchMaze(above_start_point, end_point, maze);
pathFound = pathFound || searchMaze(below_start_point, end_point, maze);
如果pathFound为true,则忽略调用。
答案 2 :(得分:1)
在else块中,如果为
设置为true1) cell_is_wall when wall is visited
2) set start_point_not_within_arrary when it is not in the array
那么你的代码应该可行。其他递归调用将由您已经拥有的这些条件检查处理。