![]() |
VOOZH | about |
Your task is to place eight queens on a chessboard so that no two queens are attacking each other. As an additional challenge, each square is either free or reserved, and you can only place queens on the free squares. However, the reserved squares do not prevent queens from attacking each other. How many possible ways are there to place the queens?
Examples:
Input:
........
........
..*.....
........
........
.....**.
...*....
........
Output: 65
Explanation: There are 65 ways to place eight queens such that no two queens attack each other.Input:
********
********
********
********
********
********
********
********Output: 0
Explanation: There is no space to put eight queens that do not attack each other.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Recursion and checking by placing queens at every possible row and column. We can start from the first row and then try to place queen in every column. Every time we place a queen in any row, we move to the next row and start placing another queen in that row. To efficiently check whether two queens are attacking each other, we can maintain three boolean arrays:
- occupiedCol[i] = true if there is a queen somewhere in the column i.
- occupiedPrimary[i] = true if there is a queen across the primary diagonal having (row + column = i). Value of (row + column) is same for all the cells lying on the same primary diagonal.
- occupiedSecondary[i] = true if there is a queen across the secondary diagonal having (row - column + 8 = i). Value of (row - column + 8 ) is same for all the cells lying on the same secondary diagonal.
Step-by-step algorithm:
Below is the implementation of the algorithm:
65
Time Complexity: O(N!), where N is the size of chessboard.
Auxiliary Space: O(N)