VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-chessboard-and-queens/

⇱ CSES Solutions - Chessboard and Queens - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Chessboard and Queens

Last Updated : 23 Jul, 2025

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?

👁 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:

  • Maintain a function solve(row) to calculate the number of ways to place queens, if we are currently at row = row.
  • If we have reached the end of the board, increment answer by 1.
  • Check if we can place a queen at the current cell or not.
  • For each row, traverse through all the columns and try to place a queen in all the cells.
  • After putting the queen, move to the next row and try to place a queen in it.
  • After counting all the paths, return the final answer.

Below is the implementation of the algorithm:


Output
65

Time Complexity: O(N!), where N is the size of chessboard.
Auxiliary Space: O(N)

Comment
Article Tags: