解决n皇后呕吐

2024-05-14 17:52:57 发布

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

我刚刚用python解决了nqueen问题。该解决方案输出用于将n个皇后放置在nXn棋盘上的解决方案总数,但尝试n=15需要一个多小时才能得到答案。有谁能看一下代码并给我一些加速这个程序的提示吗。。。。。。一个初级的python程序员。

#!/usr/bin/env python2.7

##############################################################################
# a script to solve the n queen problem in which n queens are to be placed on
# an nxn chess board in a way that none of the n queens is in check by any other
#queen using backtracking'''
##############################################################################
import sys
import time
import array

solution_count = 0

def queen(current_row, num_row, solution_list):
    if current_row == num_row:
        global solution_count 
        solution_count = solution_count + 1
    else:
        current_row += 1
        next_moves = gen_nextpos(current_row, solution_list, num_row + 1)
        if next_moves:
            for move in next_moves:
                '''make a move on first legal move of next moves'''
                solution_list[current_row] = move
                queen(current_row, num_row, solution_list)
                '''undo move made'''
                solution_list[current_row] = 0
        else:
            return None

def gen_nextpos(a_row, solution_list, arr_size):
    '''function that takes a chess row number, a list of partially completed 
    placements and the number of rows of the chessboard. It returns a list of
    columns in the row which are not under attack from any previously placed
    queen.
    '''
    cand_moves = []
    '''check for each column of a_row which is not in check from a previously
    placed queen'''
    for column in range(1, arr_size):
        under_attack =  False
        for row in range(1, a_row):
            '''
            solution_list holds the column index for each row of which a 
            queen has been placed  and using the fact that the slope of 
            diagonals to which a previously placed queen can get to is 1 and
            that the vertical positions to which a queen can get to have same 
            column index, a position is checked for any threating queen
            '''
            if (abs(a_row - row) == abs(column - solution_list[row]) 
                    or solution_list[row] == column):
                under_attack = True
                break
        if not under_attack:
            cand_moves.append(column)
    return cand_moves

def main():
    '''
    main is the application which sets up the program for running. It takes an 
    integer input,N, from the user representing the size of the chessboard and 
    passes as input,0, N representing the chess board size and a solution list to
    hold solutions as they are created.It outputs the number of ways N queens
    can be placed on a board of size NxN.
    '''
    #board_size =  [int(x) for x in sys.stdin.readline().split()]
    board_size = [15]
    board_size = board_size[0]
    solution_list = array.array('i', [0]* (board_size + 1))
    #solution_list =  [0]* (board_size + 1)
    queen(0, board_size, solution_list)
    print(solution_count)


if __name__ == '__main__':
    start_time = time.time()
    main()
    print(time.time() 

Tags: ofthetoinboardwhichforsize
3条回答

N皇后问题的回溯算法是最坏情况下的一种因子算法。所以对于N=8,8!在最坏的情况下检查解决方案的数量,N=9表示9!,等等。可以看到,可能的解决方案的数量增长得非常大,非常快。如果你不相信我的话,就去计算器前,从1开始,把连续的数字相乘。让我知道计算器的内存有多快用完。

幸运的是,并非所有可能的解决方案都必须检查。不幸的是,正确解的数目仍然遵循一个粗略的阶乘增长模式。因此,算法的运行时间以阶乘的速度增长。

因为你需要找到所有正确的解决方案,所以在加快程序的速度方面真的没什么可做的。你已经把搜索树上不可能的树枝修剪得很好了。我不认为还有什么会产生重大影响。这只是一个缓慢的算法。

我建议您查看Python源代码中的^{},以获得N皇后问题的另一个实现。

Python 2.6.5 (release26-maint, Sep 12 2010, 21:32:47) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test import test_generators as tg
>>> n= tg.Queens(15)
>>> s= n.solve()
>>> next(s)
[0, 2, 4, 1, 9, 11, 13, 3, 12, 8, 5, 14, 6, 10, 7]
>>> next(s)
[0, 2, 4, 6, 8, 13, 11, 1, 14, 7, 5, 3, 9, 12, 10]

解的数目可以用Donald Knuth的随机估计方法来估计。

从没有放置皇后开始,下一行允许的位置数为n。 随机选取其中一个位置,计算下一行的允许位置数(p),并将其乘以n,将其存储为解的总数(total=n*p),然后随机选择一个允许位置。

对于这一行,计算下一行允许的位置(p)的数量,并将此数乘以解的总数(total*=p)。重复此操作,直到无法求解电路板,在这种情况下,解的数目等于零,或者直到电路板求解完毕。

重复多次并计算平均解数(包括任何零)。这将给你一个快速和相当精确的解决方案的数量的近似值与近似值改善更多的运行你做。

我希望这是有意义的;)

相关问题 更多 >

    热门问题