有没有从 arr[0][0] 到 arr[n][n] 的“0”的方法? (不允许歪斜)
我被要求解决高级编程课程中的一个问题,即“假设从索引 [0] [0] 到索引 [n] [n] 的 0 和 1 矩阵中是否存在任何水平垂直方式的 '0? ”并引导可以通过递归函数求解。 下一堂课,老师解决了,我不明白它是如何运作的。我把代码放在下面。
#include <iostream>
#include <vector>
using namespace std;
#define N 10
bool path(int d[][N], int n, int i, int j)
{
if (i < 0 || j < 0 || i >= n || j >= n || d[i][j] == 1)
{
return false;
}
if (d[i][j] == 0)
{
d[i][j] = 1;
}
if (d[i][j] == 2)
{
return true;
}
return path(d, n, i, j + 1) || path(d, n, i, j - 1) || path(d, n, i + 1, j) || path(d, n, i - 1, j);
}
int main()
{
int n;
cin >> n;
int c[n][N];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> c[i][j];
}
}
c[n - 1][n - 1] = 2;
if (path(c, n, 0, 0))
{
cout << "YES";
}
else
{
cout << "NO";
}
return 0;
}
有人可以像我“eli5”一样向我解释一下吗?
I was asked to solve a problem in advanced programming course that was "Say if there is any horizonal-vertical way of '0's in a 0 & 1 matrix from index[0][0] to index[n][n]?" and guided that can be solve by recursive function.
In next session, the instructor solved it and I didn't understand how it works. I put the code below.
#include <iostream>
#include <vector>
using namespace std;
#define N 10
bool path(int d[][N], int n, int i, int j)
{
if (i < 0 || j < 0 || i >= n || j >= n || d[i][j] == 1)
{
return false;
}
if (d[i][j] == 0)
{
d[i][j] = 1;
}
if (d[i][j] == 2)
{
return true;
}
return path(d, n, i, j + 1) || path(d, n, i, j - 1) || path(d, n, i + 1, j) || path(d, n, i - 1, j);
}
int main()
{
int n;
cin >> n;
int c[n][N];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> c[i][j];
}
}
c[n - 1][n - 1] = 2;
if (path(c, n, 0, 0))
{
cout << "YES";
}
else
{
cout << "NO";
}
return 0;
}
Can someone explain it to my like I'm "eli5"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该算法尝试从 (0, 0) => 找到一条路径。 (n-1,n-1)。对于二维矩阵(c),0表示可以行走,1表示已经访问过或墙壁,2表示目的地。
path(c, n, 0, 0)
表示起点是(0, 0)。if (i < 0 || j < 0 || i >= n || j >= n || d[i][j] == 1)
表示如果索引超出边界或墙壁或已访问,则表明这不是有效路径。返回路径(d, n, i, j + 1) ||路径(d,n,i,j - 1)||路径(d,n,i + 1,j)|| path(d, n, i - 1, j);
表示向右、向左、向下或向上行走。如果任何方向有效,则表明存在有效路径。The algorithm tries to find a path from (0, 0) => (n-1, n-1). For the two dimension matrix (c), 0 indicates ok to walk, 1 means already visited or wall, 2 means destination.
path(c, n, 0, 0)
means to the start point is (0, 0).if (i < 0 || j < 0 || i >= n || j >= n || d[i][j] == 1)
means if the index is out of boundary or wall or visited, then it indicates this is not a valid path.return path(d, n, i, j + 1) || path(d, n, i, j - 1) || path(d, n, i + 1, j) || path(d, n, i - 1, j);
means to walk to right, left, down, or up. if any direction works, it indicates there is a valid path.