You're right to be suspicious! That output definitely indicates something is wrong with the recursion and the way you're exploring the search space. The fact that you're seeing coordinates that are clearly out of bounds (like 8, 10, 12, 14, etc. when n is likely smaller) is a huge clue.
The problem is that you've renamed check_pairs to check_queens in the recursive call, but you haven't changed the function definition. This means the recursive call is using the original check_pairs function, which is expecting a num_counts parameter that you're no longer passing.
Here's the corrected code:
int check_pairs(int n,
int current_floor,
int num_counts,
vector<pair<int, int>>& queens) // keep ref
{
// ------------------------------------------
// base-case: we placed a queen on every row
// ------------------------------------------
if (current_floor == n) // equality is enough
return 1; // found ONE valid board
int total = 0; // will collect solutions of this branch
for (int i = 0; i < n; ++i) {
pair<int, int> current_coord = {i, current_floor};
bool is_safe = true;
for (const auto& queen : queens) {
if (current_coord.first == queen.first || // same col
current_coord.second == queen.second || // same row
abs(current_coord.first - queen.first) ==
abs(current_coord.second - queen.second)) { // same diag
is_safe = false;
break; // no need to keep checking
}
}
if (is_safe) {
queens.push_back(current_coord); // choose
cout << current_coord.first << ' ' << current_coord.second << '\n';
total += check_pairs(n, current_floor + 1, num_counts + 1, queens); // Corrected recursive call
queens.pop_back(); // UN-choose (backtrack) 🔑
}
}
return total; // return all solutions found below
}
Explanation:
I changed check_queens(n, current_floor + 1, queens) back to check_pairs(n, current_floor + 1, num_counts + 1, queens). This ensures that the recursive call uses the correct function definition and passes all the necessary parameters.
With this fix, the recursion should work correctly, and you should see a more reasonable output that reflects the valid queen placements.
Debugging Tip:
When you're debugging recursive functions, it's often helpful to print the values of the parameters at the beginning of the function to see how they change with each recursive call. This can help you identify where the recursion is going wrong.