CSES – Chessboard and Queens

遞迴

#include<bits/stdc++.h>
#define int long long
#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
using namespace std;
char board[8][8];
bool put[8][8]={0};
int ans=0;
bool ok(int x,int y){
    for(int i=0;i<8;i++){
        for(int j=0;j<8;j++){
            if(put[i][j]){
                if(abs(x-i) == abs(y-j)) return false;
                if(x==i || y==j) return false;
            }
        }
    }
    return true;
}
void solve(int i){
    if(i==8){
        ans++;
        return;
    }
    for(int j=0;j<8;j++){
        if(board[i][j]=='*' || !ok(i,j)){
            continue;
        }
        put[i][j]=true;
        solve(i+1);
        put[i][j]=false;
    }
}
signed main(){
    fastio;
    for(int i=0;i<8;i++) for(int j=0;j<8;j++) cin>>board[i][j];
    solve(0);
    cout<<ans<<"\n";
    return 0;
}

相關文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *