willsun888
9/21/2013 - 1:08 PM

## 四皇后问题

``````//============================================================================
// Name        : test.cpp
// Author      : will
// Version     :
// Description : Hello World in C++, Ansi-style
//============================================================================

#include<stdio.h>
#include<stdlib.h>

#define n 4

int arr[n][n];

int isLegal(){
int i,j,
sum1 =0,	//列和
sum2 =0,	//行和
sum3 =0,        //斜行和
sum4 =0;        //反斜行和
for(i=0;i<n;i++){
for(j=0;j<n;j++){
sum1 += arr[j][i];
sum2 += arr[i][j];
if(i==j)	sum3 += arr[i][j];
if(i+j==n-1)	sum4 += arr[i][j];
}
if(sum1>1||sum2>1)
return 0;
sum1=0;
sum2=0;
}
if(sum3>1||sum4>1)
return 0;

return 1;
}

void print(){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
printf("----------\n");
}

void Trial(int i){
int j;
if(i>=n)
print();
else{
for(j=0;j<n;j++){
arr[i][j] = 1;
if(isLegal())
Trial(i+1);
arr[i][j] = 0;
}
}
}

int main(void)
{
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
arr[i][j] = 0;
}
}
Trial(0);
return EXIT_SUCCESS;
}
``````