Skip to content
Advertisement

N-Queens II using backtracking is slow

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

https://leetcode.com/problems/n-queens-ii/

My solution:

JavaScript

It fails at n=8. I can’t figure out why, and how to have less iterations. It seems I am already doing the minimum iterations possible.

Advertisement

Answer

The restricted set seems wasteful, both time- and space-wise. At the end of the successful recursion, n levels deep it grows to n^2 size, which drives the total complexity to O(n^3). And it is not really needed. It is much easier to check the availability of the square by looking at the queens already placed (please forgive the chess lingo; file stand for vertical, and rank for horizontal):

JavaScript

to be used in

JavaScript

And there is a plenty of room for the optimization. For example, you may want to special-case the first rank: due to a symmetry, you only need to inspect a half of it (cutting execution time by the factor of 2).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement