算法学习--n皇后问题

//n皇后问题
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <string>
#include <vector>
typedef int** intpp;
typedef int* intp;
using namespace std;

int n;//n*n的棋盘中,0代表空,1代表有皇后
int cnt = 0;//记录有多少个解

void show_chess(intpp chess) {//打印棋盘
	for (int i = 0; i < n; i++){
		for (int j = 0; j < n; j++) {
			cout << chess[i][j] << " ";
		}
		cout << endl;
	}
	cout << "-----------------" << endl;
}

bool canPut(intpp chess, int row, int col) {//这里注意,因为递归的时候行一直变,所以用检查行冲突
	for (int i = 0; i < n; i++) {//检查同一列
		if (chess[i][col] == 1) {
			return false;
		}
	}
	//检查对角线
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (i == row || j == col)//本身
				continue;
			if ((i + j == row + col || i - j == row - col) && chess[i][j] == 1) {//注意对角线坐标的特点
				return false;
			}
		}
	}
	return true;
}

void dfs(intpp chess, int row) {
	if (row == n) {
		cout << "第" << ++cnt << "个解:" << endl;//输出第几个解
		show_chess(chess);//打印棋盘
		return;
	}
	for (int col = 0; col < n; col++) {
		if (canPut(chess, row, col)) {
			chess[row][col] = 1;
			dfs(chess, row + 1);
			chess[row][col] = 0;//回溯
		}
	}
}

int main() {
	cin >> n;
	//定义一个n*n的棋盘
	intpp chess = new intp[n];
	for (int i = 0; i < n; i++) {
		chess[i] = new int[n];
		memset(chess[i], 0, n * sizeof(int));//初始化
	}
	dfs(chess, 0);
	return 0;
}
发布了25 篇原创文章 · 获赞 17 · 访问量 723

猜你喜欢

转载自blog.csdn.net/mu_mu_mu_mu_mu/article/details/104294140