在c++中使用回溯算法制作0hh1

Making 0h h1 using backtracking algorithm in c++

本文关键字:0hh1 回溯算法 c++      更新时间:2023-10-16

所以,当我尝试阅读和理解回溯算法时,我似乎总是失败。

我有一个制作0h h1大脑游戏的项目

求解器在c++中使用回溯算法输出所有可能的解。

关于游戏规则的快速介绍,你有一个网格(比如6x6),你必须用相等数量的红色和蓝色正方形填充每一行和每一列,记住每一列/每一行都需要不同并且你不能用相同的颜色设置三个正方形。

现在,我可以将上述条件作为函数,使用它们在主求解器函数中测试我的解,但我无法使求解算法

算法应该与以下类似:

    void try(int i)
   {
     for (int k=0;k<m-1;k++){
     select k-th candidate;
     if (acceptable){
       record it;
       if (i<n)
           try(i+1);
       else
           print solution;
       cancel recording;
        }           
     }
   }

知道怎么做吗?谢谢我希望我的解释是清楚的!

这个问题的简单回溯方法如下:

backtrack(row,col):
   if table is full: found the solution
   table[row][col] = blue // put blue here
   if no contradictions:
        backtrack(row,col+1) // or backtrack(row+1,0)
   table[row][col] = red // put red here
   if no contradictions:
        backtrack(row,col+1) // or backtrack(col+1,0)
   table[row][col] = null // clear this place to avoid false contradictions

但我不得不说,这是相当低效的。对于这类问题,最好使用约束满足启发式方法,这样可以更快地解决问题。有关更多信息,我建议您阅读Stuart RusselArtificial Intelligence: A Modern ApproachConstraint Satisfaction Problems章节。你可以在网上搜索本章的学术幻灯片。例如:
http://www.ra.cs.uni-tuebingen.de/lehre/uebungen/ws13/AI/skript/AI_06_Constraint_Satisfaction_Problems_1-30.pdf