Search code examples
c++arraysscopeiostream

Fixing input problems in C++ for reference variables


bool isSafe(char arr[][N],int r,int c)
{
//to check that queens are not in the same column
for(int i=0;i<=r;i++){
if(arr[i][c]=='Q')
return false;}

//to check that queens are not in the same left diagonal
for(int i=r,j=c;i>=0&&j>=0;i--,j--){
if(arr[i][j]=='Q')
return false;}

//to check that queens are not in the same right diagonal
for(int i=r,j=c;i>=0&&j<N;i--,j++){
if(arr[i][j]=='Q')
return false;}
}

This is a part of the code for the N Queens problem, where I define N to be 8 using #define N 8 Now, here is the following-

cout<<"The solution(s) are-"<<endl;
char arr[N][N];
memset(arr,'-',sizeof arr);         //initializes the entire n*n chessboard with '-'
solveNQueen(arr,0);

This is under the main function. But here, I define N as a constant initially and equal to 8. I can't go for a possible input statement (of N) under main as that'd cause scope problems of N in isSafe() So in this case, what should I do so that I can get the user to input the value of N through the terminal, without any problems raised?


Solution

  • The simple solution is to use a vector.

    int n;
    cin >> n;
    vector<vector<char>> v(n, vector<char>(n));
    solveNQueen(v, 0);
    
    bool isSafe(vector<vector<char>>& v,int r,int c)
    {
        int n = v.size();
        ...
    }
    

    If you need to know the size of a vector you can get it using the size method, v.size();.