1 solutions

  • 0
    @ 2023-10-31 16:28:48

    标准的dfs,开三个bool数组分别记录纵向和两个斜向的状态。

    代码如下:

    # include<iostream>
    using namespace std;
    
    int n,sum=0,a[15];
    bool row[15]={0},l[30]={0},r[30]={0};
    
    void dfs(int cnt){
    	if(cnt==n){
    		if(sum<3){
    			for(int i=0;i<n;++i) cout<<a[i]<<" ";
    			cout<<endl;
    		}
    		++sum;
    		return;
    	}
    	for(int i=0;i<n;++i){
    		if(row[i]) continue;
    		int ll=cnt-i+15,rr=cnt+i;
    		if(l[ll]||r[rr]) continue;
    		row[i]=1,l[ll]=1,r[rr]=1;
    		a[cnt]=i+1;
    		dfs(cnt+1);
    		row[i]=0,l[ll]=0,r[rr]=0;
    	}
    }
    
    int main(){
    	cin>>n;
    	dfs(0);
    	cout<<sum;
    	return 0;
    }
    
    • 1

    Information

    ID
    219
    Time
    1000ms
    Memory
    125MiB
    Difficulty
    3
    Tags
    # Submissions
    103
    Accepted
    30
    Uploaded By