N Queens Using Bit
1. You are given a number n, the size of a chess board.Input Format
2. You are required to place n number of queens in the n * n cells of board such that no queen can kill another.
Note  Queens kill at distance in all 8 directions
3. Complete the body of printNQueens function  without changing signature  to calculate and print all safe configurations of nqueens
Use sample input and output to get more idea.
Note > The online judge can't force you to write the function recursively but that is what the spirit of question is.
Write recursive and not iterative logic. The purpose of the question is to aid learning recursion, branch and bound technique, bit manipulation
and not test you.
A number nOutput Format
Safe configurations of queens as suggested in sample outputQuestion Video
1 <= n <= 10Sample Input
4Sample Output
01, 13, 20, 32, .
02, 10, 23, 31, .

Editorial
The problem here deals with solving NQueens problem using the concepts of bit manipulation. Earlier we have solved the NQueens problem using recursion and backtracking. This bit manipulation technique is just an optimization to the recursive solution so the NQueens Branch and Bound recursive solution is a prerequisite to this problem.
The N Queens problem deals with placing N Queens on a N*N board so that no two queens attack each other. A queen can attack in all 8 directions.
For example N = 4
_ _ Q _
Q _ _ _
_ _ _ Q
_ Q _ _
The above arrangement is a possible solution to the problem.
In this solution, we will be working on space optimization for the branch and bound method. So instead of creating arrays for columns, diagonals, and antidiagonal here, we will be maintained integer values which will be the binary representation analogous to that of arrays created earlier. Here an unset bit will provide us the information that position is a safe position and a set bit will imply that we need not apply recursion here as that would lead to an attack by the queen.
The rest implementation is solely based on branch and bound NQueens recursive solution.
Time Complexity: O(N!)
Each row has N positions to deal with which makes our recursive solution of the type: T(n) = n*T(n1) + k
Space Complexity: O(N*N)
A board of size N*N is created to store the result.

Asked in Companies

Related Topics