1 #include 2 #include 3 int q[11]; //q[1] means the coordinate of queue is (1, q[1]) 4 int result[11];//to save the time, so record the previous time 5 int check(int k) //check if the kth queen is conflict with previous ones 6 { 7 int i; 8 i = 1; 9 while (i < k)10 {11 //k - i == abs(q[k] - q[i]) means the current queen is not 45° with other queens12 if (q[i] == q[k] || k - i == abs(q[k] - q[i]))13 return 0;14 i++;15 }16 return 1;17 }18 //begin with the first queen, find the position for first queen19 //and use DFS to go on to find next queen's position, if u can't find it, u can go back to change the previous queen's position20 //untill there is no position for the fist queue to change 21 int Nqueens(int n)22 {23 int count, i, j, k;24 count = 0; //record the count of rank25 //begin with first queen and the zero position26 k = 1;27 q[k] = 0;28 while (k > 0)29 {30 q[k]++;31 //when q[k] <= n, u can go on to find q[k] satisfied the condition32 while (q[k] <= n && check(k) == 0)33 q[k]++;34 //if q[k] <= n, which means u can find position for current queen35 if (q[k] <= n)36 {37 //means u find the last queen, so u can record the counr38 if (k == n)39 count++;40 //if it's not the last queen, u should go on to find the place of next queen41 //and for next queen, u should begin with zero.42 else43 {44 k++;45 q[k] = 0;46 }47 }48 else49 //if u can't find the position for current queen, u should go back to modify the previous queen's position50 k--;51 }52 return count;53 }54 int main() 55 { 56 int n;57 while (scanf("%d", &n) != EOF && n)58 {59 if (result[n] == 0)60 result[n] = Nqueens(n);61 printf("%d\n", result[n]);62 }63 return 0; 64 }