八皇后问题解释:可参考八皇后问题_百度百科 (baidu.com)
总体思路:动态规划,递归,一行一行下棋
核心递归函数:
void fun(int**chess,int row,vector<int> result) {
/*
function:用于递归的函数
par:
chess:目前的棋盘
row:该下棋的行
result:存放已经放置“皇后”的列
*/
if (row == 9) {
count_sum++;
for (int i = 0; i < 8; i++) {
cout << result[i] << " ";
}
cout << endl;
return;
}
else {
for (int col = 1; col < 9; col++) { //尝试改行每一列是否可以下棋
if (chess[row][col] == 0) { //表示可以下棋
/*chess[row][col] = 1;*///此处不可赋值为1因为对列赋值的时候还会再加一遍1
result.push_back(col);
//赋值
col_assgin(chess, col,1);//全都赋值为-1
slop_assgin(chess, row, col, 1);
if (debug) {
print_chess(chess);
}
//递归:
fun(chess, row + 1, result);
//撤销:
//chess[row][col] = 0;
result.pop_back();
col_assgin(chess, col, -1);
slop_assgin(chess, row, col,-1);
if (debug) {
print_chess(chess);
}
//逻辑错误,赋值赋的位置和撤销时的位置不一定是对称的,所以改为递增赋值和递减撤销
int a = 0;
}
}
}
}
下棋后或撤销时对该位置所在列的操作函数:
void col_assgin(int**chess,int col, int value) { //对指定列进行处理,可用于赋值和撤销
for (int i = 1; i < 9; i++) {
chess[i][col] += value;
}
}
下棋后或撤销时对该位置的斜线方向的操作函数:
void slop_assgin(int** chess, int row, int col,int value) { //对斜线方向操作
int temprow = row, tempcol = col;
while (temprow != 1 && tempcol != 1) {//左上方
temprow--, tempcol--;
chess[temprow][tempcol] += value;
}
temprow = row, tempcol = col;
while (temprow != 8 && tempcol != 1) //左下方
{
temprow++, tempcol--;
chess[temprow][tempcol] += value;
}
temprow = row, tempcol = col;
while (temprow != 1 && tempcol != 8)//右上方
{
temprow--, tempcol++;
chess[temprow][tempcol] += value;
}
temprow = row, tempcol = col;
while (temprow != 8 && tempcol != 8)//右下方
{
temprow++, tempcol++;
chess[temprow][tempcol] += value;
}
}
实现结果:(仅截图了部分)