Problems/Backtracking/N Queens
Backtracking
hard

N Queens

The Knight's Harmony problem challenges you to place a given number of knights on a chessboard such that no two knights threaten each other. This tests your ability to use backtracking to explore solution spaces efficiently, a crucial skill for solving combinatorial problems.

backtrackingrecursioncombinatorialchessboardoptimization

Problem Statement

Imagine a chessboard of size N x N. Your task is to determine the total number of distinct arrangements where you can place N knights on the board, ensuring that none of the knights can attack each other. Remember, a knight attacks in an 'L' shape: two squares in one direction (horizontally or vertically) and then one square perpendicularly.

Example 1
Input: n = 1
Output: 1
With a 1x1 board, you can place one knight in the only square.
Example 2
Input: n = 5
Output: 10
On a 5x5 board, there are 10 distinct ways to position 5 knights so that no two knights can attack each other.
Constraints
  • -1 <= n <= 8
  • -The board is always square (n x n)
  • -You must place exactly 'n' knights on the board

Brute Force Approach

Think of it like trying every possible combination of spots to park N cars in a parking lot. You'd try placing the first car, then the second, and so on, checking each time if the new car is too close to any of the others. This involves checking every single possible arrangement, which is very inefficient. The time complexity is exponential, and the space complexity is constant (excluding the board representation).

TimeO(n^(n^2))
SpaceO(1)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem