ORTools和Python中的NoCycle约束

2024-09-30 18:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python中的OR工具实现Knight-Tour问题,我正在努力解决无循环约束。在C++中,存在^ {< CD1> }全局约束,并且我假设在Python包装器中,与此等价的是^ {< CD2> }约束。在

到目前为止,我得到的简化代码(我从一些失败的示例中复制了TreeNoCycle部分):

# side length of board
n = 5

# where the knight jumps to from field i, starting at 0, ending at n*n
jump_to = [solver.IntVar(1, n*n) for i in range(n*n)]

# snip other constraints

# the no cycle constraint
active = [solver.IntVar(1, 1) for i in range(dim * dim)]
for t in active:
    solver.Add(t == 1)
solver.Add(solver.TreeNoCycle(jump_to, active, lambda: None))

执行时,最后一个部分会出现以下错误:

python3.6/site-packages/ortools/constraint_solver/pywrapcp.py", line 337, in NextSolution return _pywrapcp.Solver_NextSolution(self) SystemError: returned a result with an error set

我的其余代码可以工作,也就是说,当我省略带有TreeNoCycle约束的部分时,我得到了许多解决方案,但有些解决方案带有断开的图。在

我的假设是正确的,TreeNoCycleMakeNoCycle的Python方法吗?如果是,如何正确使用TreeNoCycle?如果。如果我不能使用TreeNoCycle,有什么想法可以用不同的方式实现呢?在


Tags: theto代码inaddforrangeat