void place_queen(const int col, int queen_pos[], const int max_col) { int i, row, conflict; if (col == max_col) { for (i = 0; i < max_col; ++i) { printf("%d ", queen_pos[i]); } printf("\n"); return; } for (row = 0; row < max_col; ++row) { conflict = 0; for (i = 0; i < col && !conflict; ++i) { if (queen_pos[i] == row || abs(row - queen_pos[i]) == (col - i)) { conflict = 1; } } if (!conflict) { queen_pos[col] = row; place_queen(col + 1, queen_pos, max_col); } } }
int main(void) { int max_col = 8; int queen_pos[max_col]; place_queen(0, queen_pos, max_col); return 0; }
void main() { int n_solutions; int size=14; int board[size]; printf("size=%d\n", size); n_solutions = place_queen(0, board, size); printf("n_solutions=%d\n", n_solutions); }
void place_queen(int row){ if(row == 8){ print_column(++num); return; } for(int i = 0; i < 8; ++i){ column_row[row] = i; if(check_column(row)){ place_queen(row + 1); } } }
/************************************************************************ * n后问题求解 * input : n, the number of queens * output : the vector of solution, X ************************************************************************/ int n_queens(FILE *fp,int n,int x[]) { int nCount=0; //解个数 int k=1; //先处理第1个皇后 x[1]=0; while(k>0) { x[k]=x[k]+1;//在当前列加1的位置开始搜索 while(x[k]<=n && !place_queen(x,k)) //当前列位置是否满足条件 x[k]=x[k]+1; //不满足,继续搜索下一列位置 if(x[k]<=n) //若存在满足条件的列 { if(k==n)//是最后一个皇后,则得到一个最终解 { //break; //此处若break,则只能得到一个解 nCount++; output_queens(x,n); //输出 output_queens(fp,nCount,x,n); } else //否则,处理下一个皇后,即第 k+1 个皇后 { k++; x[k]=0; } } else //若不存在满足条件的列,则回溯 { x[k]=0; //第k个皇后复位为0 k--; //回溯到前一个皇后 } } return nCount; }
int place_queen(int column, int board[], int size) { int n_solutions = 0; int is_sol; int i, j; // Try to place a queen in each line of <column> for (i=0; i<size; i++) { board[column] = i; // Check if this board is still a solution is_sol = true; for (j=column-1; j>=0; j--) { if ((board[column] == board[j]) || (board[column] == board[j] - (column-j)) || (board[column] == board[j] + (column-j))) { is_sol = false; break; } } if (is_sol) { // It is a solution! if (column == size-1) { // If this is the last column, printout the solution n_solutions += 1; //print_solution(board, size); } else { // The board is not complete. Try to place the queens // on the next level, using the current board n_solutions += place_queen(column+1, board, size); } } } return n_solutions; }
int main(){ place_queen(0); return 0; }