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

Algorithm 递归函数中哪里需要return语句?,algorithm,recursion,depth-first-search,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

我读了这篇关于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
}
functionexploremaze(迷宫[],x,y)
{
//如果当前位置脱离网格,则
//我们不能继续走这条路

如果y>8或y,则迷宫似乎是作为文本块创建的。*用于表示墙或越界。字母“E”用于表示迷宫的出口。它可能是这样的:

********************E**
*......*......*......**
*.********.*******.****
*.....*......*........*
*.*************.*****.*
*..*............*****.*
***********************
从y8线开始,尺寸应该是8高,但你明白了。当位置是字母“E”时,找到出口,迷宫就解决了。“A”和“H”用来表示某种宽度。我不太明白,但这是相同的想法

递归的工作原理是这样的。以我的起点,比如x=7,y=6。如果它是出口,那么我们成功了。如果它在墙上,我们失败了。如果它超出边界,我们失败了,现在检查我周围的所有四个位置并做同样的事情。如果这四个位置中的任何一个找到出口,那么我们成功了

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

基本情况如下:

if maze[x][y]=='E' then return true
–如果你到达终点,你成功地解决了迷宫,因此迷宫是可解的,你返回
true
来说明这一点

现在,如果您到达了某个不是端点的点,并且递归地探索了迷宫的其余部分(这是
if
指令中发生的情况),并且您从递归调用中获得了
true
,那么递归调用成功地到达了端点。因此迷宫是可解的–返回
true

注意

给出的代码不正确:它无法正确处理无法解决的迷宫

如果迷宫不可解,或者由于缺少
'E'
位置:

******
*....*
******
或缺少适当的路径:

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

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

欢迎使用堆栈溢出。请不要链接到场外代码。请在问题主体中包含代码的相关部分。因为您的函数必须始终返回值。在不带参数的情况下使用
返回
是未定义的行为。另一方面,代码站点不是
c++
c
@4386427…如果(且仅当)函数具有返回类型
void
;-)@Scheff True…我们对此一无所知…在“if exploreMaze()之后的哪个步骤将返回True?”当x和y映射到文本迷宫中“E”的位置时。如果你想更清楚地理解递归,我建议一个更简单的例子——比如树行走。它一遍又一遍地调用自己,根据结构,它确实有效。