算法之美——八皇后

 众所周知的八皇后算法,用递归实现:

 

#include <iostream>
#include <string>
using namespace std;

#define NUM 8

int count=0;
char cache[NUM][NUM] = {0};
int level=0;
void queen(int row, int max)
{
	// 依次放置在列上;
	for (int i = 0; i < max; ++i)
	{
		// 清空当前行;
		memset(cache[row], 'x', max);

		bool fHas = false;
		// 判断同一列;
		for(int irow = 0; irow < row; ++irow)
		{
			if(cache[irow][i] == 'o')
			{
				fHas = true;
				break;
			}

			// 对角线是否有皇后;只测试row<irow的行
			int icol = i;
			if(icol + (row - irow) < max)
			{
				if(cache[irow][icol + (row - irow)] == 'o')
				{
					fHas = true;
					break;
				}
			}

			if(icol - (row - irow) >= 0)
			{
				if(cache[irow][icol - (row - irow)] == 'o')
				{
					fHas = true;
					break;
				}
			}
		}

		if(fHas)
			continue;

		cache[row][i] = 'o';

		//求出下一列的位置;
		if(row < max - 1)
		{
			level++;
			queen(row + 1, max);
		}
		if(row == max - 1)
		{
			for (int i = 0; i < max; ++i)
			{
				for (int j = 0; j < max; ++j)
				{
					cout<< cache[i][j]<< " ";
				}

				cout<< endl;
			}
			count++;
			cout<<count<< endl;
			system("pause");
		}
		
	}

}

int main(int argc, char* argv[])
{
	queen(0, NUM);
	return 0;
}

 

八皇后问题的扩展:排序大小

题目描述:

会下国际象棋的人都很清楚:皇后可以在横、竖、斜线上不限步数地吃掉其他棋子。如何将8个皇后放在棋盘上(有8 * 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题。 
对于某个满足要求的8皇后的摆放方法,定义一个皇后串a与之对应,即a=b1b2...b8,其中bi为相应摆法中第i行皇后所处的列数。已经知道8皇后问题一共有92组解(即92个不同的皇后串)。
给出一个数b,要求输出第b个串。串的比较是这样的:皇后串x置于皇后串y之前,当且仅当将x视为整数时比y小。

输入:

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数b(1 <= b <= 92)

输出:

输出有n行,每行输出对应一个输入。输出应是一个正整数,是对应于b的皇后串。

样例输入:
2
1
92
样例输出:
15863724
84136275
#include "iostream"
#include "stdio.h"
#include "math.h"
#include "vector"
#include "queue"
#include "memory.h"
#include "algorithm"
#include "string"
using namespace std;
 
int n,ind;
bool row[12],dia1[25],dia2[25];
int ans[96][10];//ans[92][8]
int res[96];

void Dfs(int q)
{   
    if(q>8)
    {
        ind++;
        for(int i=1;i<=8;i++)
            ans[ind][i]=ans[ind-1][i];
        return;
    }
    
    for(int r=1;r<=8;r++)
    {
        if(row[r]&&dia1[r+q]&&dia2[8-q+r])
        {
            row[r]=dia1[r+q]=dia2[8-q+r]=false;
            ans[ind][q]=r;
            Dfs(q+1);
            row[r]=dia1[r+q]=dia2[8-q+r]=true;
        }
    }
}

int main()
{
   memset(row,true,sizeof(row));
   memset(dia1,true,sizeof(dia1));
   memset(dia2,true,sizeof(dia2));
   ind=1;
   Dfs(1);
   
   scanf("%d",&n);
   
   int i,x;
   while(n--)
   {
        scanf("%d",&x);
        for(i=1;i<=8;i++)
            printf("%d",ans[x][i]);
        cout<<endl;
   }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值