c++实现八皇后问题

八皇后问题解释:可参考八皇后问题_百度百科 (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;
	}
}

实现结果:(仅截图了部分)

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值