如何计算nqueens问题的递归调用数?

2024-10-01 17:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码来解决n-queens问题,我应该计算递归调用的数量。我有一个名为ConstructCandidates的函数来获取候选解决方案,我试图计算它进行的递归调用的数量。我想知道我是否正确地计算了递归调用,因为我不确定我是否正确地计算了递归调用


def createChessBoard(boardSize):
   
    chessBoard = [0]*boardSize
   
    for index in range(boardSize):
        chessBoard[index] = [0]*boardSize
    return chessBoard 


def isSolution(results, numberOfQueens):
   
    if numberOfQueens==n:
        for r in results:
            for row in r:
                print(row)
            print()
    return numberOfQueens>len(results)


def safeToPlaceQueen(chessBoard, boardRow, boardColumn, boardSize):

 
    for indexColumn in range(boardColumn):
   
        if chessBoard[boardRow][indexColumn] == 1:
            return False
    
    indexRow, indexColumn = boardRow, boardColumn
    
    while indexRow >= 0 and indexColumn >= 0:
        
        if chessBoard[indexRow][indexColumn] == 1:
            return False
        
        indexRow-=1
       
        indexColumn-=1
    
    diagonalRow, diagonalColumn = boardRow,boardColumn
    
    while diagonalRow < boardSize and diagonalColumn >= 0:
        
        if chessBoard[diagonalRow][diagonalColumn] == 1:
            return False
       
        diagonalRow+=1
        
        diagonalColumn-=1
    
    return True


def ConstructCandidates(chessBoard, columnLength, boardSize):
  
    global recursionCounter
    
    
    if columnLength >= boardSize:
        return
   
    for row in range(boardSize):
        
        if safeToPlaceQueen(chessBoard, row, columnLength, boardSize):
            chessBoard[row][columnLength] = 1
            
            if columnLength == boardSize-1:
                Process(chessBoard)
                chessBoard[row][columnLength] = 0
                return
            #recursively call ConstructCandidates to find more candidate solutions
            ConstructCandidates(chessBoard, columnLength+1, boardSize)
            
            chessBoard[row][columnLength] = 0
            recursionCounter+=1


def Process(chessBoard):
   
    global results
    
    solutions = copy.deepcopy(chessBoard)
    
    results.append(solutions)

    global count 
   
    count= len(results)
    

def isFinished():
    if count >0:
        return False

n = 8

chessBoard = createChessBoard(n)

results = []

recursionCounter =0

ConstructCandidates(chessBoard, 0, n)

isSolution(results, n)

if isFinished() is False:
    print("All possible solutions without the Queen being in danger have been found")

print("The total number of possible solutions for",n,"Queens is:",len(results))

print("The total number of recursive calls to solve the problem of",n,"Queens is:",recursionCounter)

如果我做得不对,有人能告诉我怎么做吗?目前我得到的8皇后的结果是1964年


Tags: infalseforreturnifdefresultsrow

热门问题