Thanks in advance for your time :). When I tried to implement NQueens, I kinda observed a case like...instance of the variables after recursion would usually be unfolding itself in a stack manner right, so does in my case with all the variable except one 2-D array. It isn't being unfolded..instead staying the way it was at the last of the recursive call...appreciate for taking time to help, thanks =D.
Place of issue...the variable "board[100][100] " is not unfolding instead, like said, was staying at the last instance of recursive call I expect it to be like 1st queen placed, 2nd queen placed, 3rd queen placed and then 3rd queen placed, 2nd queen placed, 1st queen placed just like the placed
variable. Or I guess maybe that's how it is supposed to be working, however, I want to know the logical explanation on it's behaviour on why the "board" variable isn't unfolding.
void foo(bool board[100][100], int x, int y, int n, int m, int placed)
{
if( placed == n )
{
display(board, n, m);
return ;
}
int i, j;
for(i=x; i<=n; i++)
{
for(j=y; j<=m; j++)
{
if( checkBoard(board, n, m, i, j) )
{
board[i][j] = true;
display(board, n, m);
cout<<placed;
foo(board, 1, 1, n, m, placed+1);
display(board, n, m);
cout<<placed;
}
}
}
}
My Output -> As you can see the variable named "placed" is unfolding like expected, but it isn't in the case of this 2-D array called "board[100][100]".
Whole Code:-
#include <bits/stdc++.h>
using namespace std;
int display(bool board[100][100], int n, int m)
{
int i, j;
cout<<"\n===============================================\n\n";
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
if( board[i][j] )
{
cout<<"|Q|";
}
else
{
cout<<"|_|";
}
}
cout<<'\n';
}
cout<<"\n===============================================\n";
}
bool checkBoard(bool board[100][100], int n, int m, int x, int y)
{
int i, j;
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
if( board[i][j] and ( (x==i or y==j) or (abs(x-i)==abs(y-j)) ) )
{
return false;
}
}
}
return true;
}
void foo(bool board[100][100], int x, int y, int n, int m, int placed)
{
if( placed == n )
{
display(board, n, m);
return ;
}
int i, j;
for(i=x; i<=n; i++)
{
for(j=y; j<=m; j++)
{
if( checkBoard(board, n, m, i, j) )
{
board[i][j] = true;
display(board, n, m);
cout<<placed;
foo(board, 1, 1, n, m, placed+1);
display(board, n, m);
cout<<placed;
}
}
}
}
int main(void)
{
int i, j,
n = 4,
m = 4;
bool board[100][100];
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
board[i][j] = false;
}
}
foo(board, 1, 1, n, m, 0);
return 0;
}