算法學習--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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章