AlgoMaster Logo

N-Queens

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Backtracking Approach

The N-Queens problem is a classic problem that can be solved using a backtracking approach. The main idea is to place queens one by one in different rows, starting from the first row. When placing a queen in a particular row, we must ensure that it does not attack any other previously placed queens. For this, we can use three sets to track the columns and two diagonals (positive and negative diagonals).

Intuition:

  • Use a recursive function to place queens row by row.
  • For each row, try placing the queen in each column and check if it leads to a valid solution.
  • Use three sets to track if a queen is already placed in a column, positive diagonal, or negative diagonal.
  • If we reach the last row and place all the queens successfully, add the board configuration to the result list.
  • Backtrack: If placing a queen in a certain position doesn't lead to a solution, remove the queen (backtrack) and try the next position.

Code:

2. Optimized Backtracking with Bitmasking

For an even more optimized approach, we can use bitmasking to manage the columns and diagonals. This reduces the overhead of using sets and improves lookup times to constant.

Intuition:

  • Use bitmask integers to represent the columns, positive diagonals, and negative diagonals.
  • The idea is similar to the above approach but uses bit manipulation for checking and setting the states of columns and diagonals.

Code: