N Queen problem

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.

CODE

solveNQUtil(board, 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; // BACKTRACK
        }
    }
    return false;
}

bool isSafe(int board[N][N], int row, int col)
{
    int i, j;
 
    /* Check this row on left side for attacking queens*/
    for (i = 0; i < col; i++)
    {
        if (board[row][i])
            return false;
    }
 
    /* Check upper diagonal on left side */
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
    {
        if (board[i][j])
            return false;
    }
 
    /* Check lower diagonal on left side */
    for (i = row, j = col; j >= 0 && i < N; i++, j--)
    {
        if (board[i][j])
            return false;
    }
 
    return true;
}

Leave a comment