【发布时间】: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吗?