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

时间:2016-04-26 19:10:45

标签: python algorithm random solver n-queens

到目前为止,我有这个代码显示了针对N-Queens问题的8x8电路板的92个解决方案。而不是显示所有92个解决方案,我想尝试让它在每次运行时只显示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

1 个答案:

答案 0 :(得分:2)

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

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)