Search⌘ K
AI Features

Solve N-Queens Problem

Explore how to solve the N-Queens problem by placing N queens on an N×N chessboard so that no two queens attack each other. Learn to apply backtracking techniques to reduce unnecessary checks, understand the algorithm's recursive structure, and analyze the solution's time and space complexity. This lesson helps you develop problem-solving skills with backtracking for coding interviews.

Statement

Given a chessboard of size N×NN \times N, determine how many ways NN queens can be placed on the board, such that no two queens attack each other.

A queen can move horizontally, vertically, and diagonally on a chessboard. One queen can be attacked by another queen if it is present in the same row, column, or diagonal of that queen.

Example 1

Below is a valid placement of 44 queens on a 4×44 \times 4 chessboard. The XX on the board represents a square where a queen is placed:

g q     X         X X X
...