Sample Output
1
0
#include<iostream> |
#include<algorithm> |
using namespace std; |
const int len=10; |
int a[len][len]; |
int b[len][len]; |
int cc[len][len]; |
int dd[len][len]; |
int ee[len][len]; |
int n,cnt; |
void init() |
{ |
for ( int i=1; i<=n; i++ ) |
{ |
for ( int j=1; j<=n; j++ ) |
{ |
a[i][j]=j; |
b[i][j]=j; |
cc[i][j]=0; |
} |
} |
} |
int ok ( int r, int c, int k, int fla ) |
{ |
if ( fla ) |
{ |
if ( cc[a[r][c]][b[r][k]] ) return 0; |
for ( int i=1; i<r; i++ ) |
{ |
if ( b[i][c]==b[r][k] ) |
return 0; |
} |
} |
else |
{ |
for ( int i=1; i<r; i++ ) |
{ |
if ( a[i][c]==a[r][k] ) |
return 0; |
} |
} |
return 1; |
} |
void backtrack ( int r, int c ) |
{ |
for ( int i=c; i<=n; i++ ) |
{ |
if ( ok ( r,c,i,0 ) ) |
{ |
swap ( a[r][c],a[r][i] ); |
for ( int j=c; j<=n; j++ ) |
{ |
if ( ok ( r,c,j,1 ) ) |
{ |
swap ( b[r][c],b[r][j] ); |
cc[a[r][c]][b[r][c]]=1; |
if ( c==n ) |
{ |
if ( r==n ) |
{ |
cnt++; |
} |
else backtrack ( r+1,1 ); |
} |
else backtrack ( r,c+1 ); |
cc[a[r][c]][b[r][c]]=0; |
swap ( b[r][c],b[r][j] ); |
} |
} |
swap ( a[r][c],a[r][i] ); |
} |
} |
} |
int main() |
{ |
while ( cin>>n ) |
{ |
cnt=0; |
init(); |
backtrack ( 1,1 ); |
cout<<cnt<<endl; |
} |
return 0; |
} |