2698:八皇后问题

2698:八皇后问题

总时间限制: 
10000ms 
内存限制: 
65536kB
描述
在国际象棋棋盘上放置八个皇后,要求每两个皇后之间不能直接吃掉对方。
输入
无输入。
输出
按给定顺序和格式输出所有八皇后问题的解(见Sample Output)。
样例输入
 
   
样例输出
No. 1
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
No. 2
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 1 0 0 0 0 0 
No. 3
1 0 0 0 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
No. 4
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
No. 5
0 0 0 0 0 1 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 0 1 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
No. 6
0 0 0 1 0 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 7
0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 1 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 8
0 0 1 0 0 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 9
0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
...以下省略
提示
此题可使用函数递归调用的方法求解。
来源
计算概论05


#include "iostream"
#include "algorithm"
#include "cmath"
using namespace std;
int Map[9][9];
int T;

bool Judge(int x,int y)
{
    int i,j; 
    
	for(i=1;i<=x-1;i++) 
	{
		for(j=1;j<=8;j++)
		{
			if(Map[i][j]==1)
			{
				if(y==j ||  fabs(x-i)==fabs(y-j) )
				{
					return false;
				}
			}
		}
		
	}
    return true;
}
void Output()
{    
	cout<<"No. "<<T<<endl;
    int i,j;

	for(i=1;i<=8;i++)
	{
		for(j=1;j<=8;j++)
		{
			if(i>j)
			{
				int item;
				item=Map[i][j];
				Map[i][j]=Map[j][i];
				Map[j][i]=item;
			}
		}
	} 
    for(i=1;i<=8;i++)
	{
		for(j=1;j<=8;j++)
		{
			cout<<Map[i][j]<<" ";
		}
		cout<<endl;
	} 
	for(i=1;i<=8;i++)
	{
		for(j=1;j<=8;j++)
		{
			if(i>j)
			{
				int item;
				item=Map[i][j];
				Map[i][j]=Map[j][i];
				Map[j][i]=item;
			}
		}
	} 
	 

}
void Dfs(int x)
{     
	int i;
    if(x==9)
	{ 
	  T++;
	  Output();
	  return;
	}

	for(i=1;i<=8;i++)
    { 
	    Map[x][i]=1;
		if(Judge(x,i))
		Dfs(x+1);
		Map[x][i]=0;
	}

}
int main( ) 
{
      
    freopen("1.txt","w",stdout);
	T=0;
    Dfs(1);
    
	 


	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_34125999/article/details/51474768