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"?