Example #1
0
/* A recursive utility function to solve N Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
    /* base case: If all queens are placed then return true */
    if (col >= N)
        return true;
 
    /* Consider this column and try placing this queen in all rows
       one by one */
    for (int i = 0; i < N; i++)
    {
        /* Check if queen can be placed on board[i][col] */
        if ( isSafe(board, i, col) )
        {
            /* Place this queen in board[i][col] */
            board[i][col] = 1;
 
            /* recur to place rest of the queens */
            if ( solveNQUtil(board, col + 1) == true )
                return true;
 
            /* If placing queen in board[i][col] doesn't lead to a solution
               then remove queen from board[i][col] */
            board[i][col] = 0; // BACKTRACK
        }
    }
 
     /* If queen can not be place in any row in this colum col
        then return false */
    return false;
}
Example #2
0
bool solveNQ(){
    int board[N][N] = { {0, 0, 0, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 0}
    };
 
    if ( solveNQUtil(board, 0) == false ){
      printf("Solution does not exist");
      return false;
    }
    printSolution(board);
    return true;
}
Example #3
0
bool solveNQUtil(int board[N][N], int col){
    if (col >= N) return true;
 
    for (int i = 0; i < N; i++){
        if ( isSafe(board, i, col) ){
            board[i][col] = 1;
 
            if ( solveNQUtil(board, col + 1) == true )    return true;
 
            board[i][col] = 0; 
        }
    }
return false;
}
bool solveNQUtil(int board[N][N], int col)
{
    if (col >= N)
        return true;
    
    //check all the rows in this column
    for (int i = 0; i < N; ++i)
    {
        if (isSafe(board, i, col))
        {
            board[i][col] = 1;
            
            if (solveNQUtil(board, col + 1))   return true;
            
            //BackTracking
            board[i][col] = 0;

        }
    }
    
    return false;
}