1 条题解

  • 0
    @ 2021-6-14 23:20:22

    C :

    #include<stdio.h>
    #include<stdlib.h>
    int a[10];
    void output(int n)
    {
    	int i;
    	for(i=1;i<=n;i++)
    		printf("%d",a[i]);
    	printf("\n");
    }
    int check(int k)
    {
    	int i;
    	for(i=1;i<=k-1;i++)
    		if((abs(a[i]-a[k])==abs(i-k))||a[i]==a[k])
    			return 0;
    		return 1;
    }
    void backdate(int n)
    {
    	int k=1;
    	a[1]=0;
    	while(k>0)
    	{
    		a[k]=a[k]+1;
    		while(a[k]<=n&&check(k)==0)
    			a[k]=a[k]+1;
    		if(a[k]<=n)
            {
    			if(k==n)
    				output(n);
    			else
    			{
    				k=k+1;
    				a[k]=0;
    			}
    		}
    		else
    			k=k-1;
    	}
    }
    int main()
    {
    	backdate(8);
    	return 0;
    }
    
    

    C++ :

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    
    int r, a, b; int count = 0, ans = 0;
    
    void dfs( int row ) {
        if( row == 8 ) { count++; cout<<ans<<endl; return; }
        for( int i = 0; i < 8; ++i ) {
            if( !(r&(1<<i)) && !(a&(1<<(row+i))) && !(b&(1<<(row-i+7))) ) {
               r |= (1<<i); a |= (1<<(row+i)); b |= (1<<(row-i+7));
               ans = ans * 10 + (i+1);
               dfs(row+1);
               ans /= 10;
               r &= ~(1<<i); a &= ~(1<<(row+i)); b &= ~(1<<(row-i+7));
            }
        }
    }
    
    int main(){
        //freopen("out.txt", "w", stdout);
        dfs(0); //cout<<"一共有"<<count<<"种方法!";
        return 0;
    }
    
    
    • 1

    信息

    ID
    136
    时间
    1000ms
    内存
    128MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者