My problem should be a variant of N queens problem:
Is there an algorithm to print all ways to place N queens in a k*k chessboard?
I have tried to modify the DFS method used in the N-queens problem like the following but soon realized that I could only search the first "queen_number" of rows in the chessboard.
def dfs(self, n, queen, queen_number, ret):
if len(queen) == queen_number:
ret.append(queen[:])
return
for i in range(n):
if i in queen:
continue
flag = False
for j, idx in enumerate(queen):
if abs(len(queen) - j) == abs(idx - i):
flag = True
break
if flag:
continue
queen.append(i)
self.dfs(n, queen, ret)
queen.pop()
If there is a better way to accomplish this task, I am also interested to learn it.
I had some fun coming up with a brute force solution with this question:
As I mentioned this is a brute force solution, you can further improve it by doing 2 things.
For example if we use the algorithm for 3 queens on a 4*4 board:
You can see that all the solutions are the same solution mirrored through one of the axes of symmetry.
Using this simplification would make the code at least 8 times faster, probably more.
The limitations of the brute force algo are quite serious: