I was trying to recursively find the path from upper-left corner to lower-left corner of a grid that traverses through all values. So for example, I have a 2x2 grid, and it should go Right, Down, Left, and this is the only solution. For some reason, when I run my program I get no output after some pause, and I changed it to a smaller grid, and added the output of the direction for each recursive call for debugging purposes, but the program doesn't output anything.
Shouldn't it at least output something when it goes through the first if-statement? I'm unsure what is wrong.
#include <bits/stdc++.h>
using namespace std;
int grid[4];
vector<char> path;
int counter = 0;
void search(int n) {
if (path.size() == 3 && n == 2) {
for (auto x : path) {
cout << x;
}
cout << "\n";
}
if (path.size() == 3 || n == 2) return;
grid[n] = 1;
// Go Up
if (n-2 >= 0 && n-2 <= 3 && !grid[n-2]) {
path.push_back('U');
cout << 'U';
search(n-2);
};
path.pop_back();
// Go Down
if (n+2 >= 0 && n+2 <= 3 && !grid[n+2]) {
path.push_back('D');
cout << 'D';
search(n+2);
};
path.pop_back();
// Go Left
if (n-1 >= 0 && n-1 <= 3 && !grid[n-1]) {
path.push_back('L');
cout << 'L';
search(n-1);
};
path.pop_back();
// Go Right
if (n+1 >= 0 && n+1 <= 3 && !grid[n+1]) {
path.push_back('R');
cout << 'R';
search(n+1);
};
path.pop_back();
}
int main() {
search(0);
cout << counter;
return 0;
}