[数据结构]N-Queens Problem(recursion)

//queens.h
#pragma once
const int maxboard = 30;
class Queens
{
public:
	Queens(int size);
	bool is_solved()const;
	void print();
	bool ungarded(int col)const;//优化后
	void insert(int col);
	void remove(int col);
	void solve_from(Queens &configuration);

private:
	int board_size;
	int count;
	bool col_free[maxboard];//一些优化操作
	bool upward_free[2 * maxboard - 1];
	bool downward_free[2 * maxboard - 1];
	int queen_in_row[maxboard];

};

//queens.cpp
#include"queens.h"
#include<iostream>
using namespace std;
bool Queens::is_solved()const{
	return count == board_size;
}

void Queens::print()
{
	for (int row = 0; row < board_size; row++) {
		for (int i = 0; i < queen_in_row[row]; i++)cout << " 0 ";
		cout << " 1 ";
		for (int i = queen_in_row[row] + 1; i < board_size; i++)cout << " 0 ";
		cout << endl;
	}
	cout <<"----------------------------------------------" <<endl;
}

bool Queens::ungarded(int col) const
{
	return (col_free[col] && upward_free[count + col] && downward_free[count - col + board_size - 1]);
}

void Queens::insert(int col)
{
	queen_in_row[count] = col;
	col_free[col] = false;
	upward_free[count + col] = false;
	downward_free[count - col + board_size - 1] = false;
	count++;
}

void Queens::remove(int col)
{
	count--;
	queen_in_row[count] = 0;
	col_free[col] = true;
	upward_free[count + col] = true;
	downward_free[count - col + board_size - 1] = true;
}

void Queens::solve_from(Queens & configuration)
{
	if (configuration.is_solved());//configuration.print();
	else {
		for (int col = 0; col < board_size; col++) {
			if (configuration.ungarded(col)) {
				configuration.insert(col);
				solve_from(configuration);
				configuration.remove(col);
			}
		}
	}
}

Queens::Queens(int size)
{
	board_size = size;
	count = 0;
	for (int i = 0; i < maxboard; i++)col_free[i] = true;
	for (int i = 0; i < 2 * maxboard - 1; i++)upward_free[i] = true;
	for (int i = 0; i < 2 * maxboard - 1; i++)downward_free[i] = true;
}

//main.cpp
#include"queens.h"
#include<iostream>
#include<Windows.h>
using namespace std;
void main() {
	while (1) {
		DWORD start_time = GetTickCount();
		{
			cout << "请输入需要计算的皇后数量(maxcount=30)。" << endl;
			int count;
			cin >> count;
			Queens configuration(count);
			configuration.solve_from(configuration);
		}
		DWORD end_time = GetTickCount();
		cout << "The run time is:" << (end_time - start_time) << "ms!" << endl;//输出运行时间
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值