Eight Queens—— (The first recursion and backtracking)

Place eight queens on an 8*8 chessboard, each queen cannot appear on its own row, column, and diagonal. There are a total of 92 placement situations.

Use r to denote rows and c[r] to denote columns to determine the condition. Because r is an increasing row, only rows without a queen will be found, so there is no need to judge the number of rows, and then the condition is reduced to three:
judge the column, judge the main pair Diagonal, judge the negative diagonal...
1.c[r]==c[j] j loops before r
2.c[r]-c[j]==rj;
3.c[j]-c[r]==rj;

Look for the function, exit at 8, make a boundary, and reach backtracking.


void search(int r){
    
    
    if(r==8){
    
    
        save();
        return;
    }
    for(int i=0;i<8;i++){
    
    
        c[r]=i;
        bool ok=true;
        for(int j=0;j<r;j++)
            if(c[r]==c[j]||r-j==c[r]-c[j]||r-j==c[j]-c[r]){
    
    
                ok=false;
                break;
            }
        if(ok){
    
    
            search(r+1);
            ans=0;
        }
    }
}

The save function, with the queen's coordinates, double loop adds the value to ans, and compares the maximum value at the last time.

void save(){
    
    
    for(int i=0;i<8;i++){
    
    
        for(int j=0;j<8;j++){
    
    
            if(j==c[i]){
    
    
                ans+=a[i][j];
            }
        }
    }
    Ans=max(Ans,ans);
}

Main function, nothing to say

int main(){
    
    
    int k;cin>>k;
    while(k--){
    
    
        for(int i=0;i<8;i++){
    
    
            for(int j=0;j<8;j++){
    
    
                cin>>a[i][j];
            }
        }
        Ans=0;ans=0;
        search(0);
        cout<<setw(5)<<Ans<<endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/iuk11/article/details/107589357