简体   繁体   中英

how could I solve 0HH1 with backtracking in c++

I'm trying to solve this puzzle using backtrack algorithm. In c++ I face the problem that I couldn't apply the backtrack

void try1(int x,int y)
{  
    int k=-1;
    do{
        k++ ;
        if(check_color(c[k],x,y))
        {
            h[x][y]=c[k];// c[k]= r or b;          
           if ( check_full() && check_array() && check_equal() )
           {
               cout<<"coloring had finished"; cout<<"  \n  ";
               print(h); getch();
           }         
           else 
           {
               if(y==9&&x<9)
               {
                   y = -1; x++;
               }
               while(y<9 )
               {
                    y=y+1;
                    if(h[x][y]==' ')
                        try1(x,y);
                     /* here should be the backtrack I think
                       if(q=='n')
                      { x--;cout<<h[x][y];
                        if(h[x][y]=='b'){h[x][y]='r';}
                        else {h[x][y]='b';}}*/                 
                    else if ( y==9 && x<9 ){
                        y=-1 ;x++ ; 
                    }
                }
            }
        }
    } while ( k<1 )  ; 
}

could anyone help me??? Ineed all possible solution back tracking

Backtrack algorithm is quite simple. You just pick a move. Check if that move is okay. And then you go to next position. Here is what I think you should write.

void try1(int x,int y)
{  
    for ( int k = 0; k < 2; ++k ){
        h[x][y] = c[k];
        if ( is it okay to put this color in this position ){
            if ( x == 9 && y == 9 ){ // table is full
                // we have found the solution
                // print the table
                return;
            }
            // assuming x is the number of current row
            // assuming y is the number of current column
            // assuming we are filling the matrix from left to right
            //                                         and top to bottom
            int next_x, next_y;
            if ( y == 9 ){ 
                next_y = 0;
                next_x = x+1;
            } else {
                next_y = y+1;
                next_x = x;
            }
            try1(next_x, next_y);
        }
        h[x][y] = ' '; // clear this place
    }
}

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