Support Me...........

Please support me by giving donation

contact: aswinavofficial@gmail.com


Total Pageviews

Monday, September 1, 2014

C++ program to solve n Queens Problem

// n Queens problem #include #include using namespace std; void nQueens(int r, int n, int column[]); bool place(int r, int c, int column[]); int main() { int n; cout << "Enter number of queens: "; cin >> n; // Creating n+1 because we'll count from 1 int column[n+1]; // Place the 1st queen in the row nQueens(1, n, column); return 0; } void nQueens(int r, int n, int column[]) { int i, c; for (c=1; c<=n; c++) if (place(r, c, column)) { // placing Queen r in Row r & Column c. column[r] = c; if (r == n) // all Queens are placed. { for (i = 1; i <= n; i++) cout << "Queen no. " << i << " is placed in Row no. " << i << " and column no. " << column [i] << endl; exit(0); } else nQueens (r+1, n, column); // placing the next Queen. } } bool place(int r, int c, int column[]) { int j; for (j=1; j<=r-1; j++) if ((column[j] == c) || ((abs(column[j] - c)) == (abs(j - r)))) return false ; return true ; } // aiuto

No comments: