Tell us what’s happening:
I’ve been trying to solve this for the past few days without any tutorial and am completely stuck at this point. Is this a dead end or can I still salvage a miracle out of this?
Your code so far
from copy import deepcopy
def dfs_n_queens(n):
solutions = []
if n < 1:
return solutions
board = []
for _ in range(n):
board.append([0] * n)
indices = []
def insert_queen(queens_left, board_to_edit):
_board = deepcopy(board_to_edit)
nonlocal solutions
nonlocal indices
nonlocal n
if queens_left == 0:
if indices not in solutions:
solutions.append(deepcopy(indices))
indices.clear()
return
for a, row in enumerate(_board):
for b, _ in enumerate(row):
if queens_left == n:
_board = deepcopy(board_to_edit)
indices.clear()
if _ == 0:
indices.append(b)
_board[a] = [1] * n
for i in _board:
i[b] = 1
dri = a
dci = b
while dri >= 0 and dci >= 0 and dri < n and dci < n:
_board[dri][dci] = 1
dri += 1
dci += 1
dri = a
dci = b
while dri >= 0 and dci >= 0 and dri < n and dci < n:
_board[dri][dci] = 1
dri -= 1
dci += 1
dri = a
dci = b
while dri >= 0 and dci >= 0 and dri < n and dci < n:
_board[dri][dci] = 1
dri += 1
dci -= 1
dri = a
dci = b
while dri >= 0 and dci >= 0 and dri < n and dci < n:
_board[dri][dci] = 1
dri -= 1
dci -= 1
length = len(indices)
insert_queen(queens_left - 1, _board)
_board = deepcopy(board_to_edit)
while length < len(indices):
indices.pop()
insert_queen(n, board)
return solutions
print(dfs_n_queens(4))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:146.0) Gecko/20100101 Firefox/146.0
Challenge Information:
Implement the N-Queens Problem - Implement the N-Queens Algorithm