我试图解决N-Queens(仅1个解决方案)问题,但我成功了,但是我的程序在很长的时间内最多只能计算N = 47,因此我尝试实现最小约束值和最大约束变量尽管速度更快,但仍然很慢。我该怎么做才能计算出N = 1000?
def solve(n, x, board, mid_rows, sd_squares):
# If we are on the last row, it means we have put all the queens:
if x >= n:
print_board(board)
sys.exit(0)
for i in sd_squares:
# If we can put a queen on the current square, do it
if isOk(board, mid_rows[x], i, n):
board[mid_rows[x]][i] = 1
# Do the same thing for the next row
solve(n, x + 1, board, mid_rows, sd_squares)
# If we are here, it means we put the queen in the wrong square so we have to remove that queen
board[mid_rows[x]][i] = 0
我不能发布整个代码,因为它太长了,但是请注意isOk(board, x, y, n)
是一个函数,它告诉我们是否在x行和y列上放置一个女王/王后,它是否威胁其他女王/王后。 >
mid_rows是一个数组,其中包括中间排到中间的行,因此假设n = 5,则为[2,3,1,4,0]
,或者当n = 6时为[3,2,4,1,5,0]
。
sd_squares是一个包含侧面正方形到中间正方形的列表。就像当n = 5时为[0,4,1,3,2]
或当n = 6时为[0,5,1,4,2,3]
。