N-Queens 显示 1 个随机解决方案

N-Queens Display 1 Random Solution

到目前为止,我有这段代码显示了 8x8 板的 N-Queens 问题的 92 种解决方案。我不想显示所有 92 个解决方案,而是想尝试让它在每次 运行 时只显示 1 运行dom 解决方案。我该怎么做?

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

生成解决方案列表,然后选择一个:

solutions = []
while solver.NextSolution():
    queen_columns = [int(queens[i].Value()) for i in range(n)]
    solutions.append(queen_columns)

import random
queen_columns = random.choice(solutions)