Search code examples
pythonbacktracking

NQueens Slver in python


I am making a nQueen Problem Solver but every time I run the program it launch this error:

"tuple" has no attribute "row"

I want to know if the function place is well structure because is the one that throw the error

import sys #use of argv

#Create the object queen with the row and column
class Queen:
    def __init__(self, row, col):
        self.row = row
        self.col = col

    def __repr__(self):
        return "Row: "+ str(self.row) + " Column: " + str(self.col)

#Validate if I can place the Queen in that space, return false or true
def place(Board,row,col):
    for i in range(0,len(Board)-1):
        #Attack conditions: cant place in the same column, row and diagonal
        if (Board[i].row == row) or (Board[i].col == col) or (abs(Board[i].row - row) == abs(Board[i].col - col)):
            return False
    return True

#Recursive function that Append the queen to the board if it can be place
def NQueens(Board,n,row):
    for i in range(1,n):
        #if the row is > than n the fuction will return the list 
        if (row > n):
            return Board 
        #If it can be place we call the NQueens function with the next row
        elif place(Board,row,i):
            Queenaux = (row,i)
            Board.append(Queenaux)
            NQueens(Board,n,row+1)

#The user enter the number of queens and size of the board
n = int(sys.argv[1])
print("nQueens Problem Solver")
print("Chess Board: ",n,"x",n)
print("Number Queens:",n)
#Create the list Board
Board = []
#Start the NQueens function with row=1
Board = NQueens(Board,n,1)
#Print the queens in the board and their coordinates
print (Board)

Solution

  • Queenaux = (row,i)
    Board.append(Queenaux)
    

    Because of these lines, Board contains tuples. You must fix it by making Queenaux a Queen instance, like so:

    Queenaux = Queen(row,i)
    

    Also note that NQueens doesn't return anything so you shouldn't assign it to Board. Just call the function and let it do the modifications.