# What Is N Queen in Data Structure?

//

Scott Campbell

What Is N Queen in Data Structure?

In the field of computer science and data structures, the N Queen problem is a classic puzzle that involves placing N chess queens on an N×N chessboard in such a way that no two queens threaten each other. This means that no two queens should be able to attack each other horizontally, vertically, or diagonally.

## The Challenge

The challenge of the N Queen problem lies in finding all possible solutions for a given value of N while ensuring that the queens do not attack each other. The goal is to place all N queens on the chessboard in a way that satisfies these conditions.

## Approaches

There are several approaches to solving the N Queen problem. Let’s take a look at two commonly used methods:

### Backtracking

Backtracking is a popular algorithmic technique for solving problems by incrementally building candidates for solutions and abandoning a candidate as soon as it is determined to be unfeasible. In the case of the N Queen problem, backtracking involves recursively trying out different positions for each queen until a valid solution is found.

• Step 2: Place a queen in the first row and column.
• Step 3: Move to the next row and check if placing a queen in any column of that row would violate any constraints.
• Step 4: If no constraints are violated, place a queen in that position and move to the next row. If constraints are violated, backtrack to step 3.
• Step 5: Repeat steps 3 and 4 until all queens are placed or a solution is found.

Bitmasking is another approach often used to optimize the N Queen problem. In this method, instead of using a two-dimensional chessboard, we represent the positions of the queens using bitmasking techniques.

• Step 1: Start with an empty chessboard represented as a binary number.
• Step 2: Place a queen in the first row and update the binary number accordingly.
• Step 3: Move to the next row and update the binary number based on whether placing a queen in any column of that row would violate any constraints.
• Step 4: If no constraints are violated, update the binary number and move to the next row.

## The Complexity

The N Queen problem is known to be NP-complete, which means that there is no known polynomial-time algorithm that can solve it for all possible inputs. The backtracking approach has an exponential time complexity of O(N!), while the bitmasking approach can reduce it to O(2^N).

In conclusion, solving the N Queen problem requires careful consideration of different approaches such as backtracking and bitmasking. While it may be challenging due to its complexity, understanding these techniques can help in developing efficient solutions for similar problems in computer science and data structures.