【问题标题】:Is my recursion ok? Are there any examples that break the code?我的递归好吗?有没有破坏代码的例子?
【发布时间】:2019-08-10 10:08:45
【问题描述】:

给定一个整数方阵 A NxN,2

编写一个函数bool reachable(int A[][100], unsigned N, int sx, int sy, int target),检查是否存在从坐标为(sx,sy)的元素到值为“target”的元素的递减路径,该路径的元素形成非递减序列。

例如:

 1  0  1  0

10 15  1  1

50 20 50 50

40  0 40 60

从坐标为 (0,0) 的元素到坐标为 (0,0) 的元素存在这样的路径 target=60,但不存在从同一元素到 target=40 的元素的这种路径。

这是我的尝试:

#define N 4
#include <iostream>
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 (A[x][y] <= A[x][y + 1])
    {
        if (reachable(A, n, x, y + 1, target)) return true;
        else return false;
    }
    if (A[x][y] <= A[x + 1][y])
    {
        if (reachable(A, n, x + 1, y, target)) return true;
        else return false;     
    }
    return true;
}
int main()
{
    int A[N][N] = { { 1, 0, 2, 0},
                    {10,15, 2, 2},
                    {50,20,50,50},
                    {40, 0,40,60} };
    std::cout << reachable(A, N, 0, 0, 60);
}

是否存在破坏代码的错误和反例?我不太擅长递归。

【问题讨论】:

  • if (e) return true; else return false; 是一个不必要的冗长 return e;。
  • 如果y == n-1,请考虑y + 1 是什么。
  • 您的A[x][y+1] 案例说“如果它可能在右侧可以到达但不是,它根本无法到达”,这似乎不太正确。 (由于其未定义的行为,您的代码有时可能会产生预期的结果。)
  • 另一个问题:默认可达性真的应该是true吗?

标签: c++ matrix path maze


【解决方案1】:

考虑这个矩阵的调用reachable(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;
}

如果输入了这个 if-else 语句,代码将忽略下一个检查其他可能路径的语句。所以在我的例子中,第二条路径被完全忽略了。

这是固定的变体:

  • 添加了检查,如果 y==n-1 则不能右转,如果 x==n-1 则不能向下;
  • 在递归调用后删除了错误的返回语句;
  • 添加了最后一个返回语句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;
}

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2017-09-30
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多