简体   繁体   English

如何在C ++中使用回溯解决0HH1

[英]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 在C ++中,我面临无法应用回溯的问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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