Search⌘ K
AI Features

Solution: N-Queens II

Understand how to apply backtracking techniques to solve the N-Queens II problem efficiently. This lesson guides you through placing queens on a chessboard, checking for attacks via columns and diagonals, and using sets to track these constraints. You will learn to backtrack when no safe positions are found and how this recursive approach counts all valid placements. This step-by-step solution also covers time and space complexity considerations to enhance your problem-solving skills in combinatorial challenges.

Statement

Given an integer, n, representing the size of an n x n chessboard, return the number of distinct ways to place n queens so that no two queens attack each other. A queen can attack another queen if they are in the same row, column, or diagonal.

Constraints:

  • 11 \leq n 9\leq 9

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive solution

In order to find the optimal placement of the queens on a chessboard, we could find all configurations with all possible placements of nn queens and then determine for every configuration if it is valid or not.

However, this would be very expensive, since there would be a very large number of possible placements and only a handful of valid ones. For example, when trying to place 66 queens on a 6×66 \times 6 ...