n皇后算法之一

本文通过C++实现N皇后问题的解决方法,并以四皇后为例展示所有可能的摆放方案。文章详细介绍了如何确保皇后间不发生冲突的条件判断,以及采用回溯算法实现的完整代码。

N皇后描述: 任何一行一列  45度斜线上都只能有一个皇后

要求: 以四皇后为例打印出符合条件的所有结果

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

const int N = 4; //number of the box
int row[N+1] = {0};


void print()
{
	cout <<"\n=========print graph begin=================\n";
	for(int i=1; i<=N; i++)
	{
		for (int j=1; j<=N; j++)
		{
			if(row[i]==j)
			{
				cout << "1\t";
			}
			else
			{
				cout << "0\t"; 
			}
			
		}
		cout << endl;
	}
	cout <<"=========print graph end====================\n\n";
}
	

bool  PositionOk(int pos, int totalNum)
{
	for(int i=1; i<pos;i++)
	{
		if(row[i]==row[pos] || abs(row[pos]-row[i])==pos-i)
		{
			return false;
		}	
	}
	return true;
}

void  rn_queens(int currentNum , int totalNum)
{
	for(row[currentNum]=1; row[currentNum]<=totalNum; row[currentNum]++)
	{	
		if(PositionOk(currentNum,totalNum))
		{
			if(currentNum == totalNum)
			{
				for(int i=1; i<=totalNum; i++)
				{
					cout << row[i] << "\t";
				}
				cout << endl;
				print();
			}
			else
			{
				rn_queens(currentNum+1,totalNum);
			}
		}
	}
}

void n_queens(int totalNum)
{
	rn_queens(1,totalNum);
}



int main()
{
	n_queens(N);
	cout << "hello world" << endl;
	return 0;
}

显示结果如下:



说明:45度斜线判断 | f(y)  - f(X) | = | y-x |

总结:回溯算法的常用形式

假设某个回溯算法其解有形式

x[1] x[2] x[3]..x[n]

再假定x[i]的值实在集S里,于是回溯算法的一般形式如下

backtrack(n)
{
	rbacktrack(1,n)
}

rbacktrack(k,n)
{
	for each x[k] belongto S
		if(bound(k))
		{
			if(k==n)
			{
				print result
			}
			else
			{
				rbacktrack(k+1,n)
			}
		}
}

其中回溯算法的一个关卡就在编写一个高效的界定函数bound

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值