试问这该咋改

P1219 [USACO1.5] 八皇后 Checker Challenge

FIGFUH001 @ 2023-12-23 11:48:07

#include<iostream>
#include <cstdio>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
const int N=20;
char g[N][N];
bool col[N],dg[N],udg[N];
int n,num=1;
void dfs(int u){
    if(u==n){
//      cout<<"No. "<<num<<endl; 
        for(int i=0;i<n;i++){
            puts(g[i]);

        }num++;
        return;
    }for(int i=0;i<n;i++){
        if(!col[i]&&!dg[u+i]&&!udg[n-u+i]){
            g[i][u]='1';            
            col[i]=dg[u+i]=udg[n-u+i]=true;
            dfs(u+1);
            col[i]=dg[u+i]=udg[n-u+i]=false;
            g[i][u]='0';
        }
    }
}

int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            g[j][i]='0';
        }
    }dfs(0);
    return 0;
}

by jayket @ 2023-12-25 00:26:00

@hoper007不要用字符数组来存字符,你这存档不都是1?存i进数组就好了; 应该是n+u-i而不是n-u+i; 不用拿二维数组存,可以拿一维数组存,每一次找到就输出,限制输出三次即可;


by jayket @ 2023-12-25 00:26:49

#include<bits/stdc++.h>
using namespace std;
const int maxn=37;
int n;
int c[17];
bitset<maxn>lin;
bitset<maxn>lef;
bitset<maxn>rig;

int cnt=0;
int kk=0;
void dfs(int row){
    if(row>n){
        if(cnt<3){
            for(int i=1;i<=n;++i)cout<<c[i]<<" ";
            ++cnt;
            cout<<"\n";
        }
        ++kk;
        return;
    }
    for(int i=1;i<=n;++i){
        if(!lin[i]&&!lef[i+row]&&!rig[row-i+n]){
            c[row]=i;
            lin[i]=1;
            lef[i+row]=1;
            rig[row-i+n]=1;
            dfs(row+1);
            lin[i]=0;
            lef[i+row]=0;
            rig[row-i+n]=0;
        }
    }
}

int main(void){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n;
    dfs(1);
    cout<<kk;
    return 0;
}

by FIGFUH001 @ 2023-12-31 11:50:24

@jayket ok


|