1
到目前为止,我有这个代码显示N-Queens问题的8x8板卡的92个解决方案。我不想显示所有92种解决方案,而是希望尝试让它每次运行时只显示一个随机解决方案。我怎样才能做到这一点?N皇后显示1随机解决方案
import sys
from ortools.constraint_solver import pywrapcp
# by default, solve the 8x8 problem
n = 8 if len(sys.argv) < 2 else int(sys.argv[1])
# creates the solver
solver = pywrapcp.Solver("n-queens")
# creates the variables
# the array index is the row, and the value is the column
queens = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
# creates the constraints
# all columns must be different
solver.Add(solver.AllDifferent(queens))
# no two queens can be on the same diagonal
solver.Add(solver.AllDifferent([queens[i] + i for i in range(n)]))
solver.Add(solver.AllDifferent([queens[i] - i for i in range(n)]))
# tells solver what to solve
db = solver.Phase(queens, solver.CHOOSE_MIN_SIZE_LOWEST_MAX, solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
# iterates through the solutions
num_solutions = 0
while solver.NextSolution():
queen_columns = [int(queens[i].Value()) for i in range(n)]
# displays the solutions
for i in range(n):
for j in range(n):
if queen_columns[i] == j:
print "Q",
else:
print "_",
print
print
num_solutions += 1
solver.EndSearch()
print
print "Solutions found:", num_solutions
这似乎工作对我非常好!但是,现在有一个错误,说'int'对象不可迭代'在num_solutions + = 1行代码旁边......我该如何解决这个问题? – Rataiczak24
那么,如果你不需要num_solutions,只需删除该行 –
好吧,我删除它,一切工作正常,没有错误...但我仍然需要打印在底部找到的解决方案的数量...哪个变量我是否在我的印刷声明中使用? – Rataiczak24