Poj1321:棋盘问题

1321:棋盘问题

总时间限制: 
1000ms 
内存限制: 
65536kB
描述
在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。
输入
输入含有多组测试数据。
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。
输出
对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。
样例输入
2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1
样例输出
2
1
来源
蔡错@pku
#include "iostream"
#include "string.h"
#include "stdio.h"
using namespace std;
char Map[8][8];
bool Heng[8],Shu[8];
int n,k;
int Num=0;
void Dfs(int x,int y,int count)
{   
    int Sum=0;
    if(count==k)
    {
    	Num++;
    	return;
    }
    if(x==n) return ;

 	int dx,dy;
	if(y==n-1)
    {
    	dx=x+1;
    	dy=0;
    }
    else
    {
    	dx=x;
    	dy=y+1;
    }
    if(x==-1 && y==-1)
	{
		dx=0;
		dy=0;
	} 	
	if(Map[dx][dy]=='#' &&  !Heng[dx] && !Shu[dy] )
	{ 
	     Heng[dx]=true;
	     Shu[dy]=true;
	     Dfs(dx,dy,count+1);
		 Heng[dx]=false;
		 Shu[dy]=false; 
	} 
    Dfs(dx,dy,count);
}



int main()
{  

     //freopen("1.txt","r",stdin);
    
	  
	while(cin>>n>>k && n!=-1 && k!=-1)
	{ 
	    int i,j;	 
		Num=0;   
	    memset(Heng,false,sizeof(Heng));
	    memset(Shu,false,sizeof(Shu));
	    for(i=0;i<n;i++)
	    for(j=0;j<n;j++)
	    cin>>Map[i][j];
        Dfs(-1,-1,0);
	    cout<<Num<<endl;
	
	}
	
	
	
	 return 0; 
}


优化
:
#include "iostream"
#include "string.h"
#include "stdio.h"
using namespace std;
int M,N;
char Map[9][9];
 
int P;
bool Shu[8];
void Dfs(int x,int y,int count)
{  
        if(count==N)
        {
        	P++;
        	return ;
        }	  
        int i,j;
        for(i=x;i<=M;i++)
        {
        	for(j=1;j<=M ;j++)
        	{
        		 if(Map[i][j]=='#'&& !Shu[j])
        		 {  
        		        
        		        Shu[j]=true;
        		        Dfs(i+1,j,count+1);		 	  
        		 	    Shu[j]=false;
        		 }
        	}
        }	
}

int main()
{
    
    //freopen("1.txt","r",stdin);
	
	while(cin>>M>>N && M!=-1 && N!=-1)
	{
		 int i,j;
		 P=0;
	 
		 memset(Shu,false,sizeof(Shu));
		 for(i=1;i<=M;i++)
		 for(j=1;j<=M;j++)
		 cin>>Map[i][j];	 		 
	     
	     Dfs(1,1,0);
	     
	     
		 cout<<P<<endl;
	} 
	 
	 
	
	return 0;
}

猜你喜欢

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