在使用N_Queens完成递归时遇到问题

时间:2018-11-09 19:08:00

标签: python-3.x n-queens

我正在处理N_Queens问题,并认为我使用递归和回溯在代码中迷失了自己。

我正在尝试不使用任何导入功能或高级语言来解决此问题。我已经感到非常沮丧,希望能通过任何解决方案和提出的宝贵意见对我有所帮助。

        global N 
N = 8

board =      [[0,0,0,0,0,0,0,0], 
              [0,0,0,0,0,0,0,0], 
              [0,0,0,0,0,0,0,0], 
              [0,0,0,0,0,0,0,0], 
              [0,0,0,0,0,0,0,0], 
              [0,0,0,0,0,0,0,0], 
              [0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0]]

def printboard(board): 
    for row in range(N): 
        for col in range(N): 
            print(board[row][col], end=' ') 
        print('')



def SafePosition(board, row, col): 

  return (board[row][col]==0)

  def AddQueen(board, row, col):
    K = row+col
    L = row-col
    for row in range(N): 
        for col in range(N): 
          if (row+col == K) or (row==row) or (col==col) or (row-col == L):
            board[row][col] = 1       
    board[row][col] = 2

def findCol(board, col):
  for row in range(N):
    if(board[col][row] == 0):
      return [row]




def SolveNQueens(): 
  findCol(board, col)
  if board[row][col] == 0:
    AddQueen(board,row,col)
    if SafePosition(board,row, col):
      board[row][col]= 2
      SolveNQueens()
      board[row][col] = 0
    return



  printboard(board)

SolveNQueens()

它首先说'Col'没有定义,这使我感到困惑,其次我似乎无法从这种当前状况中前进。

理想情况下,董事会应在女王放置的每个位置放置一个2。

请放心,我才刚刚开始学习Python3。

1 个答案:

答案 0 :(得分:1)

SolveNQueens()在代码运行时首先被调用,并且第一条语句为findCol(board, col),直到这一点我们只定义了全局变量Nboard,但没有col的定义。
但是,rowcol 是在其他函数中定义的,因此也许我们也可以将这些定义放在SolveNQueens()函数中以清除该错误,例如:< / p>

def SolveNQueens():
    columns = [col for col in range(N)] # using previous definitions from 
    rows = [row for row in range(N)]    # printboard(board) function

    # can use one range here because board is a square
    # with same length sides columns and rows
    # either len(rows), or len(columns)

    for i in range(len(rows)):
        row = rows[i]   
        col = columns[i]

        # now we have row, col available
        findCol(board, col)
        ...