简体   繁体   中英

Solving the N-queens using Python(Coding alternatives):

I tried the following code.If there are any modifications to be made it can be made to reduce the complexity of the code.I have used a nested dictionary named board.

def initialize(board,n):
   for key in ['queen','row','col','nwtose','swtone']:
     board[key] = {}
   for i in range(n):
     board['queen'][i] = -1
     board['row'][i] = 0
     board['col'][i] = 0
   for i in range(-(n-1),n):
     board['nwtose'][i] = 0
   for i in range(2*n-1):
     board['swtone'][i] = 0

def printboard(board):
   for row in sorted(board['queen'].keys()):
     print((row,board['queen'][row]))

def free(i,j,board):
   return(board['queen'][i] == 0 and board['row'][i] == 0 and board['col'][j] == 0 and board['nwtose'][j-i] == 0 and board['swtone'][j+i] == 0)

def addqueen(i,j,board):
   board['queen'][i] = j
   board['row'][i] = 1 
   board['col'][j] = 1 
   board['nwtose'][j-i] = 1 
   board['swtone'][j+i] = 1 

def undoqueen(i,j,board):
   board['queen'][i] = -1
   board['row'][i] = 0 
   board['col'][j] = 0 
   board['nwtose'][j-i] = 0 
   board['swtone'][j+i] = 0


def placequeen(i,board):
   n = len(board['queen'].keys())
   for j in range(n):
        if free(i,j,board):
         addqueen(i,j,board)
         if i == n-1:
           return(True)
         else :
           extendsoln = placequeen(i+1,board)
         if extendsoln:
           return(True)
         else:
           undoqueen(i,j,board)
   else:
      return(False)


board = {}
n = int(input("How many Queens? "))
initialize(board,n)
if placequeen(0,board):
  printboard(board)

So When I tried this code I am able to give the input say 4 but not get the output. Where excatly am I going wrong???

Thanks

When you initialize the board in initialize() you set all the values board['queen'][i] to -1 . Your main program calls if placequeen(0,board): which for each value of j calls if free(i,j,board): which checks board['queen'][i] == 0 . That last check fails for all j , so free() returns False , and placequeen never adds a queen thus returns False , and your main program never even tries to print the board.

Your program is more complicated than needed: I see no need at all for your dictionary and you can just have your various arrays as separate variables. However, you did not actually ask for simplification of your code. I am not sure how you can remove this non-print bug, but consider setting board['queen'][i] to 0 rather than -1 .

I agree with @RandomDavis that you need to learn how to use a debugger. I used one to find the cause of your stated bug, but others may remain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM