VOOZH about

URL: https://www.geeksforgeeks.org/dsa/8-queen-problem/

⇱ 8 queen problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

8 queen problem

Last Updated : 25 Sep, 2025

Given an 8x8 chessboard, the task is to place 8 queens on the board such that no 2 queens threaten each other. Return a matrix of size 8x8, where 1 represents queen and 0 represents an empty position.

👁 ApronusDiagram1595653398

Approach:

The idea is to use backtracking to place the queens one by one on the board. Starting from the first row, we try placing queens in different columns and check if it's safe (not under attack from previously placed queens). If a safe position is found, we move to the next row. If at any point no safe position exists in a row, we backtrack to the previous row and try a different column placement. This recursive approach systematically explores all possible configurations until a valid solution is found.

Step by step approach:

  1. Initialize an empty 8×8 chessboard with all positions set to 0.
  2. Start with the first row (row 0) and try placing a queen in each column.
  3. For each placement, check if the position is safe (not attacked by any previously placed queen). A position is unsafe if another queen is in the same column or on the same diagonal.
  4. If a safe position is found, place the queen (set position to 1) and recursively try to place queens in subsequent rows. Otherwise, backtrack by removing the queen and trying the next column.
  5. If all rows are successfully filled (8 queens placed), a valid solution is found.

Output
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 

Related Articles:

Comment
Article Tags: