Las Vegas算法八皇后问题最好的一种实现

#include "pch.h"
#include <iostream>
#include <vector>
#include <random>
#include <ctime>
#include <time.h>
#include <set>
#include <sys/timeb.h>
using namespace std;


#define NUMOFQUEEN 8

//uniform返回1到x的一个数


int uniform(int x,int &seeds) {
	uniform_int_distribution<int> u(1, x);
	default_random_engine e(seeds++);
	 
	return u(e);
}

bool QueensLV2(int &searchNode) {
	

	set<int> col, diag45, diag135;//分别是已用的列、45度方向的行列之差、135度方向的行列之和
	vector<int> tryV(NUMOFQUEEN+1);//(k,tryV[k})表示第k的皇后放置的位置
	int k = 0;//行号
	int j = 0;//列号
	//毫秒级时间戳,用于生成随机数
	struct timeb tp;
	ftime(&tp);
	int seeds = tp.time / 1000 + tp.millitm;.//随机数初始种子

	while (k < NUMOFQUEEN) {
		
		int nb = 0;//nb表示当前行可以放置的位置数目
		for (int i = 1; i <= NUMOFQUEEN; ++i) {
			if (col.find(i)==col.end()&&diag45.find(i-k-1)==diag45.end()&&diag135.find(i+k+1)==diag135.end()) {
				++nb;
				if (uniform(nb,seeds) == 1)//从nb的位置中随机返回一个
					j = i;
			}
		}
		if (nb > 0) {
			k++;
			tryV[k] = j;//将列号记录下来
			col.insert(j);
			diag45.insert(j - k);
			diag135.insert(j + k);
			++searchNode;//搜索节点增加
		}
		if (nb == 0)
			break;
	}

	
	if (k == NUMOFQUEEN)
		return true;
	else
		return false;

}
int main() {
	clock_t start, finish;
	double totaltime;
	start = clock();//开始时钟
	//生成棋盘,每位初始化为0,表示没有占用,1表示占用。
	//vector<vector<int>> chessBox(NUMOFQUEEN, vector<int>(NUMOFQUEEN));
	//回溯法
	//backTrack(chessBox);
	//打印
	//print(chessBox);

//测试平均搜索节点
	int sum = 0;
	for (int  i = 0; i < 1000; ++i) {
		int searchNode = 0;
		while (!QueensLV2(searchNode));
		sum += searchNode;
	}
	cout << sum/1000 << endl;
	



	finish = clock();//结束时钟
	totaltime = (double)(finish - start) ;
	cout << "程序运行时间:" << totaltime << "毫秒" << endl;

	return 0;
}


猜你喜欢

转载自blog.csdn.net/dididisailor/article/details/83038632