Recursion
1 // Solution N Queens 2 // recursive method . 3 #include <stdio.h> . 4 #include <stdlib.h> . 5 const int N = 20 is ; . 6 int Q [N]; . 7 void DISP ( int n-) { . 8 static int COUNT = 0 ; . 9 int I; 10 the printf ( " % d of th solution: " , ++ COUNT); . 11 for (I = . 1 ; I <= n-; I ++ ) 12 is the printf ( "(% D% D) " , I, Q [I]); 13 is the printf ( " \ n- " ); 14 } 15 int Place ( int K, int J) { // Test (k, j) position can be placed Queen 16 int I = . 1 ; . 17 the while (I < K) { 18 is IF ((Q [I] == J) || (ABS (Q [I] - J) == ABS (Ki))) // same column or the same diagonal . 19 return 0 ; 20 is I ++ ; 21 is } 22 is return . 1 ; 23 is } 24 void Queen ( int K, int n-) { // placed Queen 1 ~ k recursive implementation 25 int J; 26 is IF (K> n-) 27 DISP (n-); 28 the else { 29 for (J = . 1 ; J <= n-; J ++ ) { 30 IF (Place (k, j)) { // find a suitable position (k, j) at the k-th row 31 is Q [k] = J; 32 Queen (k + . 1 , n-); 33 } 34 } 35 } 36 } 37 [ int main () { 38 is int n; 39 the printf ( " Please enter a value of n \ NN = " ); 40 Scanf ( " % D " , & n); 41 is Queen ( . 1 , n); 42 is return 0 ; 43 } 44