Solution

Code

``````#include <bits/stdc++.h>
using namespace std;

int queen_in_rows[8];
bool col_free[8], upward_free[15], downward_free[15];
bool can_change[8];

void print_board() {
int i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < queen_in_rows[i]; j++)
printf(".");
printf("Q");
for (j = queen_in_rows[i] + 1; j < 8; j++)
printf(".");
printf("\n");
}
}

void solution() {
stack<pair<int, int> > S;
pair<int, int> P;
int row, col;
S.push(make_pair(0, 0));
while (1) {
P = S.top();    S.pop();
row = P.first;
col = P.second;
// 如果全部处理完了, 退出
if (row == 8) break;
// 如果当前行输入中已给出, 直接处理下一行
if (!can_change[row]) {
// cout << "can't change line " << row << endl;
S.push(make_pair(row + 1, 0));
continue;
}
// 如果该行之前放置过皇后, 那么将该皇后拿起, 然后查找位置从下一列开始
if (queen_in_rows[row] != -1) {
queen_in_rows[row] = -1;
col_free[col] = true;
upward_free[row + col] = true;
downward_free[row - col + 7] = true;
col++;
}
// 尝试寻找可以放置皇后的位置
while (col < 8) {
if (col_free[col] && upward_free[row + col]
&& downward_free[row - col + 7])
break;
col++;
}
// 如果没有找到, 则返回上一行处理
if (col == 8)
continue;
// 如果找到了, 则将皇后放入
// cout << "line " << row << " put queen in " << col << endl;
queen_in_rows[row] = col;
col_free[col] = false;
upward_free[row + col] = false;
downward_free[row - col + 7] = false;
// 保存当前行的信息, 然后查找下一行
S.push(make_pair(row, col));
S.push(make_pair(row + 1, 0));
}
while (!S.empty())
S.pop();
print_board();
}

int main(void) {
int i, k, row, col;
for (i = 0; i < 8; i++) {
queen_in_rows[i] = -1;
col_free[i] = true;
upward_free[i] = true;
downward_free[i] = true;
can_change[i] = true;
}
for (i = 8; i < 15; i++) {
upward_free[i] = true;
downward_free[i] = true;
}
scanf("%d", &k);
while (k--) {
scanf("%d %d", &row, &col);
queen_in_rows[row] = col;
can_change[row] = false;
col_free[col] = false;
upward_free[row + col] = false;
downward_free[row - col + 7] = false;
}
solution();
}``````

0条评论