This Code is solution of n-queen problem.
Solving the problem I found that the output changes depends on global variable ans initialization.
If ans initialized before grid and input value is 8, the output value is 28.
If ans initialized after grid and input value is 8, the output value is 92.
I guess its memory problem but I'm not sure exactly.
Why does the output value change depending on the position of the Initialization statement?
#include <cstdio>
using namespace std;
int ans = 0;
bool grid[14][14] = { false, };
int N;
bool isValid(int i, int cnt) {
int x, y;
for (x = 0; x < cnt; x ) {
if (grid[i][x]) return false;
}
for (x = cnt - 1, y = i - 1; y >= 0; x--, y--) {
if (grid[y][x]) return false;
}
for (x = cnt - 1, y = i 1; y < N; x--, y ) {
if (grid[y][x]) return false;
}
return true;
}
void dfs(int cnt) {
int i;
// basecase
if (cnt == N) {
ans ;
return;
}
for (i = 0; i < N; i ) {
if (!grid[i][cnt] && isValid(i, cnt)) {
// constraint satisfied
grid[i][cnt] = true;
dfs(cnt 1);
grid[i][cnt] = false;
}
}
}
int main() {
scanf("%d", &N);
dfs(0);
printf("%d ", ans);
return 0;
}
CodePudding user response:
Your program has undefined behavior. This is because at some points inside the isValid function you're using negative indices while accessing array grid's elements. You can verify this by printing the value of x(which you then use in grid[i][x]) and notice that there are some negative values. This will result in undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing is a result of undefined behavior. And as i said don't rely on the output of a program that has UB.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
