好一道深搜

    xiaoxiao2021-03-25  112

    就是一个四乘四的方格,然后最左上角的位置是1,其他位置是2-16,问在最左上角是1的前提下,任意行列,正负对角线相等的情况有多少种?

    我曹,跑了整整两分二十五秒。

    #include<iostream> #include<stdlib.h> #include<string.h> #include<stdio.h> using namespace std; int a[5][5],book[50]; int count=0; int col[5]={0}; //col[i] 表示第i列的和 int row[5]={0}; //row[i] 表示第i行的和 int check() { if(row[0]==row[1] && row[0]==row[2] && row[0]==row[3]) ; else return 0; if(col[0]==col[1] && col[0]==col[2] && col[0]==col[3]) ; else return 0; if(row[0]==col[0]) ; else return 0; if(row[0]==(a[0][0]+a[1][1]+a[2][2]+a[3][3]) && row[0]==(a[0][3]+a[1][2]+a[2][1]+a[3][0])) ; else return 0; return 1; } void DFS(int i,int j) { //printf("i=%d j=%d\n",i,j); if(i>=3 && j>3) { //cout<<666<<endl; if(check()) count++; return ; } if(j>3) { DFS(i+1,0); return ; } if(i==2) //两个剪枝 { if(row[0]!=row[1]) return ; } if(i==3) { //if(row[0]!=row[1]) return ; if(row[1]!=row[2]) return ; } int k; for(k=2;k<=16;k++) { if(book[k]==0) { book[k]=1; a[i][j]=k; col[j]+=k; row[i]+=k; DFS(i,j+1); book[k]=0; col[j]-=k; row[i]-=k; } } } int main() { memset(book,0,sizeof(book)); a[0][0]=1; col[0]=1; row[0]=1; DFS(0,1); cout<<count<<endl; return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-26041.html

    最新回复(0)