簡體   English   中英

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

[英]how could I solve 0HH1 with backtracking in c++

我正在嘗試使用回溯算法來解決這個難題。 在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 )  ; 
}

誰能幫助我??? 加強所有可能的解決方案追溯

回溯算法非常簡單。 您只需選擇一個步驟。 檢查該舉動是否還可以。 然后您轉到下一個位置。 這是我認為您應該寫的。

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