简体   繁体   中英

Making 0h h1 using backtracking algorithm in c++

So as many times as I tried reading and understanding the backtracking algorithm, I always seem to fail.

I have a project to make 0h h1 brain game

solver in c++ using backtracking algorithm to output all possible solutions.

a quick introduction about the rules of the game, you have a grid(say 6x6) and you have to fill each of each of its rows and columns with an equal number of red and blue squares, keeping in mind that each column/row needs to be different than the others, and that you can't set three squares with the same color.

Now I was able to make the conditions above as functions to use them to test my solutions in the main solver function, yet I wasn't able to make the solving algorithm

the algorithm should be similar to this:

    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;
        }           
     }
   }

Any idea how to do it? Thanks! and I hope my explanation was clear!

The simple backtrack approach for this problem would be something like this:

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

But I have to say this is rather inefficient. For this kind of problems it is better to use constraint satisfaction heuristics which result in a faster solution. For more information I suggest that you read Constraint Satisfaction Problems chapter of Artificial Intelligence: A Modern Approach by Stuart Russel . You can find the academic slides of this chapter online by searching it on the internet. Such as:
http://www.ra.cs.uni-tuebingen.de/lehre/uebungen/ws13/AI/skript/AI_06_Constraint_Satisfaction_Problems_1-30.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM