ernie.WPI.EDU> cat queens.C // file queens.C, cs2223, D97/98 // // class 26 - N-queens problem // 24Apr98 NW, First version // include #include "headers.h" // global value unsigned long int counter; // count iterations vector column; // the column vector // prototype int queens(int, int); // check partial solution of N-queens problem // main int main () { while (1) { int n; cout << endl << "enter a value of n: "; cin >> n; if (n <= 0) return 0; // exit criterion column.resize(n); // resize the column vector for (int i = 0; i < n; i++) column[i] = i; // fill the vector counter = 0; if (queens(0, n)) // found a solution { cout << "this solution was found in " << counter << " tests" << endl; for (int i = 0; i < n; i++) cout << setw(3) << column[i]; cout << endl; } else { cout << "no solution could be found in " << counter << " tests" << endl; } } } // end main() int queens(int k, int n) // N-queens test { // n is the length of the vector, k is the position to begin testing if (k == n) return 1; // checking is complete - the solution has been found for (int j = k; j < n; j++) // otherwise, permute and check the following queens { int temp = column[k]; column[k] = column[j]; column[j] = temp; // swap int conflicts = 0; // flag to keep track of conflicts if (k != 0) for (int i = k-1; i >= 0; i--) // don't need to check when k == 0 { counter++; // keep track of diagonal tests if ((column[i] == column[k] - (k - i)) || (column[i] == column[k] + (k - i))) // conflict { conflicts = 1; break; // no need to look further } } if (!conflicts && queens(k+1, n)) return 1; // solution found temp = column[k]; column[k] = column[j]; column[j] = temp; // not found, swap back } return 0; // no solution found } // end queens() // Copyright 1998 Norman Wittels ernie.WPI.EDU> g++ queens.C ernie.WPI.EDU> a.out enter a value of n: 1 this solution was found in 0 tests 0 enter a value of n: 2 no solution could be found in 2 tests enter a value of n: 3 no solution could be found in 8 tests enter a value of n: 4 this solution was found in 18 tests 1 3 0 2 enter a value of n: 5 this solution was found in 14 tests 0 2 4 1 3 enter a value of n: 6 this solution was found in 165 tests 1 3 5 0 2 4 enter a value of n: 7 this solution was found in 52 tests 0 2 4 6 1 3 5 enter a value of n: 8 this solution was found in 1032 tests 0 4 7 5 2 6 1 3 enter a value of n: 9 this solution was found in 494 tests 0 2 5 7 1 3 8 6 4 enter a value of n: 10 this solution was found in 1391 tests 0 2 5 7 9 4 8 1 3 6 enter a value of n: 15 this solution was found in 37279 tests 0 2 4 1 9 11 13 3 12 8 5 14 6 10 7 enter a value of n: 20 this solution was found in 8519585 tests 0 2 4 1 3 12 14 11 17 19 16 8 15 18 7 9 6 13 5 10 enter a value of n: -3 ernie.WPI.EDU>