N皇后问题之盲目的枚举

在本机测试到7个是没问题的,8就GG了

#include<iostream>
using namespace std;
#define QUEENNUM 8
//盲目的枚举算法
int line0[QUEENNUM]={0};
int line1[QUEENNUM]={0};
int line2[QUEENNUM]={0};
int line3[QUEENNUM]={0};
int line4[QUEENNUM]={0};
int line5[QUEENNUM]={0};
int line6[QUEENNUM]={0};
int line7[QUEENNUM]={0};
int line[QUEENNUM]={0};

void PrintFun()
{
	for(int i=0;i<QUEENNUM;i++)
	{
		if(line0[i]==1) line[0]=i;
		if(line1[i]==1) line[1]=i;
		if(line2[i]==1) line[2]=i;
		if(line3[i]==1) line[3]=i;
		if(line4[i]==1) line[4]=i;
		if(line5[i]==1) line[5]=i;
		if(line6[i]==1) line[6]=i;
		if(line7[i]==1) line[7]=i;
	}
	for(int j=0;j<QUEENNUM;j++)
	{
		printf("%d ",line[j]);
	}
	printf("\n");
}

bool IsOk()
{
	int chessboard[QUEENNUM][QUEENNUM]={0};
	for(int n=0;n<QUEENNUM;n++)
	{
		chessboard[0][n]=line0[n];
		chessboard[1][n]=line1[n];
		chessboard[2][n]=line2[n];
		chessboard[3][n]=line3[n];
		chessboard[4][n]=line4[n];
		chessboard[5][n]=line5[n];
		chessboard[6][n]=line6[n];
		chessboard[7][n]=line7[n];
	}

	for(int i=0;i<QUEENNUM;i++)
	{
		for(int j=0;j<QUEENNUM;j++)
		{
			if(chessboard[i][j]==1)
			{
				for(int k=1;k<QUEENNUM;k++)
				{
					int ipos=(i+k)%QUEENNUM;
					int colnum=abs(i-ipos);
					if(chessboard[ipos][j]==1)
					{
						return false;
					}
					if((j+colnum)<QUEENNUM)
					{
						if(chessboard[ipos][j+colnum]==1)
							return false;
					}
					if((j-colnum)>=0)
					{
						if(chessboard[ipos][j-colnum]==1)
							return false;
					}
				}
			}
		}
	}
	return true;
}

int main()
{
	long lcount=0;
	for(int i0=0;i0<QUEENNUM;i0++)
	{
		line0[i0]=1;
		for(int i1=0;i1<QUEENNUM;i1++)
		{
			line1[i1]=1;
			for(int i2=0;i2<QUEENNUM;i2++)
			{
				line2[i2]=1;
				for(int i3=0;i3<QUEENNUM;i3++)
				{
					line3[i3]=1;
					for(int i4=0;i4<QUEENNUM;i4++)
					{
						line4[i4]=1;
						for(int i5=0;i5<QUEENNUM;i5++)
						{
							line5[i5]=1;
							for(int i6=0;i6<QUEENNUM;i6++)
							{
								line6[i6]=1;
								for(int i7=0;i7<QUEENNUM;i1++)
								{
									line7[i7]=1;
									if(IsOk()) 
									{
										lcount++;
										PrintFun();
									}
									line7[i7]=0;
								}
								line6[i6]=0;
							}
							line5[i5]=0;
						}
						line4[i4]=0;
					}
					line3[i3]=0;
				}
				line2[i2]=0;
			}
			line1[i1]=0;
		}
		line0[i0]=0;
	}

	cout<<"共"<<lcount<<"种解法."<<endl;

	return 0;
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页