dfs#8T了,求助

P1219 [USACO1.5] 八皇后 Checker Challenge

likai2591 @ 2023-02-26 18:13:16

1.01s,非常极限

#include<bits/stdc++.h>
#define ull unsigned long long 
#define ll long long
using namespace std;

int n,i,num;
int arr[14][14];
int c[14];

void printResult(){
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            if(arr[i][j]!=0)
                cout<<j<<" ";
    cout<<endl; 
}

//若可以放置,则返回true 
bool check(int r,int c){
    //行、列肯定可以满足
    //主对角线
    int num=0;
    int a=r,b=c;
    while(a>=1&&b>=1){
        num+=arr[a][b];
        a--;b--;
    }
    if(num!=0)return false;
    a=r,b=c;
    while(a<=n&&b<=n){
        num+=arr[a][b];
        a++;b++;
    }
    if(num!=0)return false;
    //副对角线
    a=r,b=c;
    while(a<=n&&b>=1){
        num+=arr[a][b];
        a++;b--;
    }
    if(num!=0)return false;
    a=r,b=c;
    while(a>=1&&b<=n){
        num+=arr[a][b];
        a--;b++;
    }
    if(num==0)return true;
    else return false;
}

void search(int k){
    if(k==n+1){
        if(i<3){
            printResult();
            i++;
        }
        num++;
    }else{
        for(int j=1;j<=n;j++){
            if(c[j]==0&&check(k,j)){//若满足规则可以放置 
                arr[k][j]=1;//放置 
                c[j]=1;
                search(k+1);
                arr[k][j]=0;//还原 
                c[j]=0;
            }
        }
    }
}

int main(){
    cin>>n;
    search(1);
    cout<<num;
    return 0;
}

by Jorylee @ 2023-02-26 18:56:49

吸氧


by newtocpp @ 2023-04-27 22:29:57

@Jorylee 谢谢


|