Beispiel #1
0
 void solve() {
     if (count == size) {
         vector<string> r;
         for (int i = 0; i < size; ++i) {
             string c(size, '.');
             c[queens[i]] = 'Q';
             r.push_back(c);
         }
         result.push_back(r);
     } else {
         for (int col = 0; col < size; ++col) {
             if (col_free[col] && upward_free[count+col] &&
                 downward_free[count-col+size-1]) {
                 add_queen(col);
                 solve();
                 remove_queen(col);
             }
         }
     }
 }
Beispiel #2
0
/*
 *  make the next solve move
 */
int solve_next_move()
{
	int moved = 0;
	int on; 

	// done - found solution
	if(queen == SOLVE_NQUEENS)
	{
		sprintf(move_buff[(move_count++)%MOVE_WRAP], "Complete!!!");
		return 1;
	} 
	// done - did not find solution
	if(queen < 0)
	{
		sprintf(move_buff[(move_count++)%MOVE_WRAP], "Failed.");
		return -1;
	}

	// should only run once or twice
	while(!moved)
	{
		on = queen_on(queen);
		moved = 1;
		// from last time
		if(on)
		{
			remove_queen(queen); 
		}
		// add to board
		else
		{
			stack[queen].di = rand()%SOLVE_SIZE;
			stack[queen].dj = rand()%SOLVE_SIZE;
			stack[queen].i = 0;
		}

		// find open spot
		do
		{
			// increment position
			++stack[queen].j;
			if(stack[queen].j == SOLVE_SIZE){
				stack[queen].j = 0;
				++stack[queen].i;

				// exhausted - backtrack
				if(stack[queen].i == SOLVE_SIZE)
				{
					stack[queen].i = stack[queen].j = -1;
					--queen;
					if(on){
						mn = 0;
						sprintf(move_buff[(move_count++)%MOVE_WRAP],
								"...Exhausted spaces for Queen %d.", queen+2);
						return 0;
					}
					mn = 1;
					sprintf(move_buff[(move_count++)%MOVE_WRAP],
							"...No place for Queen %d.", queen+2);

					moved = 0;
					break;
				}
			}
		} while(!solve_spot_open(Si(queen), Sj(queen)));
	}
	mn = 0;
	sprintf(move_buff[(move_count++)%MOVE_WRAP], 
			"Move Queen %d to %c%d.", queen+1, Si(queen)+'A', Sj(queen)+1);

	// place queen
	set_queen(queen);

	// get next queen
	++queen;

	return 0;
}