×

N-Queens Algorithm

Problem Definition

The N-Queens problem is to place N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, no two queens can share the same row, column, or diagonal.

Backtracking Approach

We use a backtracking algorithm that places queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens.

Validation Check

Before placing a queen, we check if the current position is safe by verifying that no other queen is in the same row, column, or diagonal.

Recursive Placement

If placing a queen doesn't lead to a solution, we backtrack and try a different position for the previously placed queen. This process continues until we find all possible solutions.

Solution Found

When all N queens are placed successfully without threatening each other, we record the solution and continue searching for more arrangements.

Optimization

The algorithm is optimized by checking only the left side for attacking queens, since we place queens from left to right. This reduces the number of checks needed.

N-Queens Visualizer

The N-Queens problem is the challenge of placing N chess queens on an N×N chessboard so that no two queens threaten each other

0
Solutions
4
Queens
4×4
Board Size

About the N-Queens Problem

The N-Queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.

The problem was first proposed in 1848 by the chess composer Max Bezzel, and over the years, it has become one of the most famous problems in computer science and mathematics.

Key facts about the N-Queens problem:

Solutions