递归函数在哪里需要return语句?

时间:2019-03-29 12:24:41

标签: algorithm recursion depth-first-search

我阅读了有关topcoder递归和迷宫求解器解决方案中的这篇文章,我不明白为什么在“ if ExploreMaze()”语句之后需要“ return true”语句,因为它们已经在基数之后给出了条件。

function exploreMaze(maze[][],x,y)
{
  // If the current position is off the grid, then
  // we can't keep going on this path
  if y>8 or y<1 or x<'A' or x>'H' then return false

  // If the current position is a '*', then we
  // can't continue down this path
  if maze[x][y]=='*' then return false

  // If the current position is an 'E', then 
  // we're at the end, so the maze is solveable.enter code here
  if maze[x][y]=='E' then return true

  // Otherwise, keep exploring by trying each possible
  // next decision from this point.  If any of the options
  // allow us to solve the maze, then return true.  We don't
  // have to worry about going off the grid or through a wall - 
  // we can trust our recursive call to handle those possibilities
  // correctly.

  if exploreMaze(maze,x,y-1) then return true  // search up
  if exploreMaze(maze,x,y+1) then return true  // search down
  if exploreMaze(maze,x-1,y) then return true  // search left
  if exploreMaze(maze,x+1,y) then return true  // search right

  // None of the options worked, so we can't solve the maze
  // using this path.

  return false
}

2 个答案:

答案 0 :(得分:0)

看起来迷宫被创建为文本块。 *用于指示墙或超出范围。字母“ E”用于表示迷宫的出口。可能看起来像这样:

********************E**
*......*......*......**
*.********.*******.****
*.....*......*........*
*.*************.*****.*
*..*............*****.*
***********************

从y <1 y> 8行开始,尺寸应为8高,但是您可以理解。当位置为字母“ E”时,将找到出口,并迷宫解决。 “ A”和“ H”用于指示某种宽度。我不太明白,但这是相同的想法。

递归是这样的。以我的出发点为例,假设x = 7,y = 6。如果这是出口,那我们就成功了。如果是在墙上,我们就失败了。如果超出范围,则我们失败了,现在检查我周围的所有四个位置并执行相同的操作。如果这四个位置中的任何一个找到出口,那么我们就成功了。

如果迷宫是可解的,那么我们得到“真”,如果分支是可解的,那么我们得到真。如果迷宫不能从给定的起始位置解开,则返回false,如果分支不通向出口,则返回false。

答案 1 :(得分:0)

基本案例在这里:

if maze[x][y]=='E' then return true

–如果到达端点,则设法解决了迷宫问题,因此迷宫问题可以解决,并返回true来说明问题。

现在,如果到达尚未达到终点的 some 点,然后递归地探索迷宫的其余部分(这是if指令中发生的事情),则您得到了{ {1}}从递归调用,然后该递归调用设法到达端点。因此迷宫是可解决的–返回true

注意

显示的代码为不正确:无法正确处理无法解决的迷宫。

如果迷宫不解,则可能是由于缺少true位置:

'E'

或缺少适当的路径:

******
*....*
******

代码将“永远”重复出现,直到堆栈溢出,然后崩溃。