【问题标题】:N-Queens Display 1 Random SolutionN-Queens 显示 1 随机解
【发布时间】:2016-04-26 19:10:45
【问题描述】:

到目前为止,我的这段代码显示了 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

【问题讨论】:

    标签: python algorithm random solver n-queens


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 这似乎对我很有效!但是,现在 num_solutions += 1 行代码旁边显示“'int' object is not iterable”的错误...我该如何解决?
    • 好吧,如果你不需要 num_solutions,就删除那一行
    • 好的,我删除了它,一切正常,没有错误......但我仍然需要打印底部找到的解决方案数量......我在打印语句中使用哪个变量?
    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2011-05-18
    相关资源
    最近更新 更多