如何解决修改后的皇后区问题的布尔表达式
我从here看到了N皇后问题的布尔表达式。
我修改的N个皇后规则比较简单:
对于p * p棋盘,我想以这样的方式放置N个皇后区,
- 皇后将相邻放置,行将首先填充。
- p * p棋盘的大小将进行调整,直到可以容纳N个皇后为止。
例如,假设N = 17,那么我们需要一个5 * 5的棋盘,放置位置将是:
Q_Q_Q_Q_Q
Q_Q_Q_Q_Q
Q_Q_Q_Q_Q
Q_Q_*_*_*
*_*_*_*_*
问题是我正在尝试针对此问题提出布尔表达式。
解决方法
可以使用Python软件包humanize
和omega
解决此问题。
"""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 = '''
(p * p >= {q}) # chessboard fits the queens,and
/\ ((p - 1) * (p - 1) < {q}) # is the smallest such board
'''.format(q=q)
u = ctx.add_expr(s)
d,= list(ctx.pick_iter(u)) # assert unique solution
p = d['p']
print('chessboard size: {p}'.format(p=p))
# compute number of full rows
ctx.declare(x=(0,p))
s = 'x = {q} / {p}'.format(q=q,p=p) # integer division
u = ctx.add_expr(s)
d,= list(ctx.pick_iter(u))
r = d['x']
print('{r} rows are full'.format(r=r))
# compute number of queens on the last row
s = 'x = {q} % {p}'.format(q=q,p=p) # modulo
u = ctx.add_expr(s)
d,= list(ctx.pick_iter(u))
n = d['x']
k = r + 1
kword = humanize.ordinal(k)
print('{n} queens on the {kword} row'.format(
n=n,kword=kword))
if __name__ == '__main__':
q = 10 # number of queens
pick_chessboard(q)
用二进制决策图表示乘法(以及整数除法和模)在变量数量上具有复杂度指数,如https://doi.org/10.1109/12.73590
所示版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。