Implement the N-Queens Problem - Implement the N-Queens Algorithm

Tell us what’s happening:

I use an array on line 49 with constant indices and on line 58 with variables. Same array, but it works on line 49 and raises TypeError not subscriptable. I believe my alorithm is correct, but this stops me in translating the results into the simpler result vector. I need help resolving this.

Your code so far

# N-Queen solver for NxN boards using depth-first search
def Q_safe(board, row, col, n):#determine if a placing is safe
# horizontal check
    for j in range(col):
        if board[row][j] == 1:
            return False
#check upper left
    i, j = row-1, col-1
    while i >= 0 and j >= 0:
        if board[i][j] == 1:
            return False
        i -= 1
        j -= 1
#check lower left
    i, j = row+1, col-1
    while i < n and j >= 0:
        if board[i][j] == 1:
            return False
        i += 1
        j -= 1

    return True

def dfs_n_queens(n): 
    if n < 1: return []     #trivial cases
    if n == 1: return [[0]]
    if n == 2: return []
    if n == 3: return []
# algorithm starts here
    board = [[0] * n for _ in range(n)]   
    placings = []
# track placings 
    rows = set()
    diag1 = set() #row - col is constant
    diag2 = set() #row + col is constant

    def backtrack(col): #no need for safe check, built-in here
        if col >= n:
            placings.append([row[:] for row in board])
            return
        
        for row in range(n):
            if Q_safe(board,row,col,n):
                board[row][col] = 1
                backtrack(col + 1)
                board[row][col] = 0

    backtrack(0)
    print('0',placings[0],placings[0][0],placings[0][0][2])
    result = placings
    np = len(placings)
    ind = -1
    for i in range(0,np-1):
        result[i] = [0]*(n)
        print('res',result)
        for j in range(0,n-1):
            for k in range(0,n-1):
                if placings[i][j][k]==1:
                    result[i][j]=k
            

    return result

print(dfs_n_queens(4))



Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0

Challenge Information:

Implement the N-Queens Problem - Implement the N-Queens Algorithm

Consider the following example:

a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
b = a
b[0] = 0
print(a)  # ?

What value will have a?

a will be the original list

I don’t see the connection, since I am not assigning anything to the array placings

You mean [[1, 2, 3], [1, 2, 3], [1, 2, 3]]? Try the code and see.

Are you assigning placings to anything?