I am working on a project that requires me to solve the n-queens problem efficiently using Python. I have already implemented a basic recursive algorithm to generate all possible solutions, but I am looking for ways to optimize the code to handle larger values of n (i.e., n >= 20) without causing a stack overflow or taking an unreasonable amount of time to run.
My current algorithm works by generating all possible permutations of the n queens on an n x n chessboard and then checking each permutation to see if it is a valid solution. However, this approach quickly becomes computationally expensive for larger values of n.
I have read about techniques such as backtracking, pruning, and bit manipulation that can be used to optimize this problem, but I am not sure how to implement them in Python. Can someone provide an efficient algorithm for solving the n-queens problem in Python, along with a detailed explanation of how it works and why it is efficient? Also, how can I handle cases where n is very large, such as n = 100 or more?
Wikipedia's article on Eight queens puzzle gives a greedy algorithm for any (greater than 3):
Implementation
Here is an implementation in Python of the above algorithm. It first defines some constants depending on mod 6, and then constructs the solution from ranges whose boundaries are derived from these constants. The solution is run for several values of , and each is verified with a naive check:
This outputs:
NB: a number at index means there is a queen at (, ), and these coordinates are 0-indexed.