首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修正皇后问题的布尔表达式

修正皇后问题的布尔表达式
EN

Stack Overflow用户
提问于 2020-08-20 05:50:43
回答 1查看 120关注 0票数 1

我从这里中看到了N皇后问题的布尔表达式。

我修改的N皇后规则更简单:

对于一个p*p棋盘,我想用这样的方式放置N个皇后,以便

  1. 皇后区将相邻放置,行将首先填充。
  2. p*p棋盘大小将被调整,直到它能容纳N个皇后。

例如,假设N= 17,那么我们需要一个5*5的棋盘,其位置将是:

代码语言:javascript
复制
Q_Q_Q_Q_Q
Q_Q_Q_Q_Q
Q_Q_Q_Q_Q
Q_Q_*_*_*
*_*_*_*_*

问题是,我正试图为这个问题找到一个布尔表达式,

EN

回答 1

Stack Overflow用户

发布于 2020-09-10 01:02:09

这个问题可以使用Python humanizeomega来解决。

代码语言:javascript
复制
"""Solve variable size square fitting."""
import humanize
from omega.symbolic.fol import Context


def pick_chessboard(q):
    ctx = Context()
    # compute size of chessboard
    #
    # picking a domain for `p`
    # requires partially solving the
    # problem of computing `p`
    ctx.declare(p=(0, q))
    s = f'''
       (p * p >= {q})  # chessboard fits the queens, and
       /\ ((p - 1) * (p - 1) < {q})  # is the smallest such board
       '''
    u = ctx.add_expr(s)
    d, = list(ctx.pick_iter(u))  # assert unique solution
    p = d['p']
    print(f'chessboard size: {p}')
    # compute number of full rows
    ctx.declare(x=(0, p))
    s = f'x = {q} / {p}'  # integer division
    u = ctx.add_expr(s)
    d, = list(ctx.pick_iter(u))
    r = d['x']
    print(f'{r} rows are full')
    # compute number of queens on the last row
    s = f'x = {q} % {p}'  # modulo
    u = ctx.add_expr(s)
    d, = list(ctx.pick_iter(u))
    n = d['x']
    k = r + 1
    kword = humanize.ordinal(k)
    print(f'{n} queens on the {kword} row')


if __name__ == '__main__':
    q = 10  # number of queens
    pick_chessboard(q)

用二进制决策图表示乘法(以及整数除法和模)在变量数上具有指数复杂性,如以下所示:https://doi.org/10.1109/12.73590

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63499032

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档