简体   繁体   English

N女王显示1个随机解

[英]N-Queens Display 1 Random Solution

So far I have this code that displays the 92 solutions for an 8x8 board for the N-Queens problem. 到目前为止,我有这段代码可以显示针对N-Queens问题的8x8开发板的92个解决方案。 Instead of displaying ALL 92 solutions, I am wanting to try and get it to just display 1 random solution each time it is ran. 我不想显示所有92个解决方案,而是希望每次运行时仅显示1个随机解决方案。 How can I do this? 我怎样才能做到这一点?

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

Generate the list of solutions, then pick one: 生成解决方案列表,然后选择一个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM