Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我的递归可以吗?有没有任何例子打破了这一规则?_C++_Matrix_Path_Maze - Fatal编程技术网

C++ 我的递归可以吗?有没有任何例子打破了这一规则?

C++ 我的递归可以吗?有没有任何例子打破了这一规则?,c++,matrix,path,maze,C++,Matrix,Path,Maze,给定一个平方整数矩阵a NxN,2=n)返回false; 如果(A[x][y]==目标)返回true; 如果(A[x][y]认为该矩阵的调用可到达(A,N,0,0,2): 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 2 您的代码将遵循路径{0,0}->{0,1}->{0,2}->{0,3}->{1,3}->{2,3},然后返回false。出现问题的原因是此语句: if (A[x][y] <= A[x][y + 1]) { if (reac

给定一个平方整数矩阵a NxN,2=n)返回false; 如果(A[x][y]==目标)返回true;
如果(A[x][y]认为该矩阵的调用
可到达(A,N,0,0,2)

1  1  1  1

1  0  0  1

1  0  0  0

1  1  1  2
您的代码将遵循路径{0,0}->{0,1}->{0,2}->{0,3}->{1,3}->{2,3},然后返回false。出现问题的原因是此语句:

if (A[x][y] <= A[x][y + 1])
{
  if (reachable(A, n, x, y + 1, target)) return true;
  else return false;
}

<代码> >(e)返回true;否则返回false;是不必要的冗长< <代码>返回e;<代码> >考虑“<代码> y+1 >是<代码> y==n-1 < /代码>。您的<代码> [x] [y+2] < /Cord>事例说“如果它可能是可到达的右边,但不是,它根本不能到达”,这似乎不太正确。(由于未定义的行为,您的代码有时可能会产生预期的结果。)另一个问题:默认可达性真的应该是
true
if (A[x][y] <= A[x][y + 1])
{
  if (reachable(A, n, x, y + 1, target)) return true;
  else return false;
}
bool reachable(int A[N][N], int n, int x, int y, int target)
{
  if (x < 0 || y < 0 || x >= n || y >= n)
    return false;

  if (A[x][y] == target)
    return true;

  // if possible to turn right, check this path
  if (y + 1 < n && A[x][y] <= A[x][y + 1])
  {
    if (reachable(A, n, x, y + 1, target))
      return true;
  }

  // if possible to turn down, check this path
  if (x + 1 < n && A[x][y] <= A[x + 1][y])
  {
    if (reachable(A, n, x + 1, y, target))
      return true;
  }

  // no path exists
  return false;
}