Given an integer N denoting a N * N chess-board, the task is to count the number of ways to place two queens on the board such that, they do no attack each other.
Input: N = 9
There are 2184 ways to place two queens on 9 * 9 chess-board.
Input: N = 3
There are 8 ways to place two queens on 3 * 3 chess-board.
Naive Approach: A simple solution will be to choose two every possible position for the two queens on the N * N matrix and check that they are not in horizontal, vertical, positive diagonal or negative diagonal. If yes then increment the count by 1.
Time Complexity: O(N4)
Efficient Approach: The idea is to use combinations to compute the possible positions of the queens such that they do not attack each other. A useful observation is that it is quite easy to calculate the number of positions that a single queen attacks. That is –
Number of positions a queen attack = (N - 1) + (N - 1) + (D - 1) Here, // First N-1 denotes positions in horizontal direction // Second N-1 denotes positions in vertical direction // D = Number of positions in positive and negative diagonal
If we do not place the queen on the last row and the last column then the answer will simply be the number of positions to place in a chessboard of (N-1)*(N-1), whereas if we place in the last column and last row then possible positions for queens will be 2*N – 1 and attacking at 3*(N – 1) positions. Therefore, the possible positions for the other queen will be N2 – 3*(N-1) – 1. Finally, there are (N-1)*(N-2) combinations where both queens are on the last row and last column. Therefore, the recurrence relation will be –
Q(N) = Q(N-1) + (N2-3*(N-1)-1)-(N-1)*(N-2) // By Induction Q(N) = (N4)/2 - 5*(N3)/3 + 3*(N2)/2 - N/3
Below is the implementation of the above approach:
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.