我做了一个简单的迷宫搜索算法,盲目地跑到一个单元格的每个方向来检查是否找到了目标。它可以找到目标,但解决方案仍然很糟糕,因为它不会在找到目标时终止其他递归调用,并且它会绘制它已经走过的所有路径,而不仅仅是一条通往目标的可能路径。我该如何改进呢?
伪代码中的基本算法是这样的:
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);
}
}
}
}