八皇后问题解法

#include <stdio.h> #include <list> using std::list; int selcol(int* board, int dim, int row, int initcol) { for (int i=initcol; i<dim; ++i) { int j; for (j=0; j<row; ++j) { if (*(board+j*dim+i) != 0) break; if (i-(row-j)>=0 && *(board+j*dim+i-(row-j))!=0) break; if (i+(row-j)<dim && *(board+j*dim+i+(row-j))!=0) break; } if (j == row) { *(board+row*dim+i) = 1; return i; } } return -1; } int _tmain(int argc, _TCHAR* argv[]) { int n; list<int> ans; int sol_num = 0; printf("please enter number of queens:"); scanf("%d", &n); if (n <= 0) { printf("must be positive number/n"); exit(1); } int* p = new int[n*n]; if (!p) { printf("allocate memory error!/n"); exit(1); } memset(p, 0, n*n*sizeof(int)); int i = 0; int j = 0; while (i != n) { int col = selcol(p, n, i, j); if (col != -1) { ans.push_back(col); if (ans.size() == n) { printf("find solution:/n"); list<int>::iterator it = ans.begin(); for (; it!=ans.end(); ++it) { for (int i=0; i<(*it); ++i) printf("^"); printf("*"); for (int i=(*it)+1; i<n; ++i) printf("^"); printf("/n"); } ++sol_num; *(p+i*n+ans.back()) = 0; j = ans.back() + 1; ans.pop_back(); } else { j = 0; ++i; } } else { if (i == 0) break; *(p+(i-1)*n+ans.back()) = 0; j = ans.back() + 1; ans.pop_back(); --i; } } printf("%d solutions in total/n", sol_num); delete[] p; return 0; }  

你可能感兴趣的:(delete,iterator,include)