回溯法解决8皇后问题

#include <iostream>
#define N 8
using namespace std;
int position[N][N];
void Initial_position()
{
	for(int i = 0;i < N;i++)
	{
		for(int j = 0;j < N;j++)
		{
			position[i][j] = 0;
		}
	}
}
void print()
{
	for(int i = 0;i < N;i++)
	{
		for(int j = 0;j < N;j++)
		{
			cout<<position[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}
bool Judge(int x,int y)
{
      for(int k = 0;k < N && k != y;k++)
      {
		   if(position[x][k]) return false;
	   }
       for(int k = 0;k < N && k != x;k++)
	   {
		   if(position[k][y]) return false;
	   }
	   int num,num1;
	   num = x;
       num1 = y;
       while(num > 0 && num1 >0)
	   {
		   num--;
		   num1--;
		   if(position[num][num1]) return false;
	   }
	   num = x;
	   num1 = y;
	   while(num > 0 && num1 < N-1)
	   {
		   num--;
		   num1++;
		   if(position[num][num1]) return false;
	   }
	   num = x;
	   num1 = y;
	   while(num < N-1 && num1 > 0)
	   {
		   num++;
		   num1--;
		   if(position[num][num1]) return false;
	   }
	   num = x;
	   num1 = y;
	   while(num < N-1 && num1 < N-1)
	   {
		   num++;
		   num1++;
		   if(position[num][num1]) return false;
	   }
	   return true;
}
int number = 0;
void BT(int num1,int num2,int temp[N][N])
{
	if(num1 == N)
		{
			print();
			number++;
	}
	else
	{
		for(int i = 0;i < N;i++)
		{
			if(Judge(num1,i))
			{
				temp[num1][i] = 1;
				//print();
				BT(num1+1,0,temp);
				temp[num1][i] = 0;
			}
		}
	}
}

int main()
{
	Initial_position();
	print();
	BT(0,0,position);
	cout<<"共有"<<number<<"种解法!"<<endl;
	system("pause");
	return 0;
}
    原文作者:回溯法
    原文地址: https://blog.csdn.net/N1neDing/article/details/78408091
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞