Tell us what’s happening:
What’s going on? I genuinely cannot find any difference in what the stories are asking for and what the function is returning
Your code so far
cols = set()
diag1 = set()
diag2 = set()
solutions = []
def dfs_n_queens(n):
if n < 1:
return []
current = [] # store column for each row
def is_safe(row, col):
return (col not in cols and
(row - col) not in diag1 and
(row + col) not in diag2)
def solve(row):
if row == n:
solutions.append(current.copy())
return
for col in range(n):
if is_safe(row, col):
# place
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)
current.append(col)
solve(row + 1)
# undo
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
current.pop()
solve(0)
return solutions
print(dfs_n_queens(5))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0
Challenge Information:
Implement the N-Queens Problem - Implement the N-Queens Algorithm