POJ-1321, the board issues (DFS)

Description:

In a checkerboard given shape (the shape may be irregular) placed above the pieces, pieces no difference. The requirements of any two pieces can not be placed in the same row or the same column in the board when the display is required, program for solving a given board size and shape, placing the k pieces of all possible placement scheme C. 

Input: 

Test input comprising a plurality of sets of data.
The first line of each data are two positive integers, NK, separated by a space, and indicates the number of the board will be described in a matrix of n * n, and put the pieces. n <= 8, k <= n
when the end of input is represented by -1 -1.
Then n lines describe the shape of a checkerboard: n characters per line, where # represents the board area, indicates a blank area (extra blank line data is guaranteed not to appear or blank columns).  

Output: 

For each set of data, one line of output is given, the number of output display program C (data guarantee C <2 ^ 31). 

Sample Input: 

2 1

#.

.#

4 4

...#

..#.

.#..

#...

-1 -1 

Sample Output: 

2

code: 

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char map[10][10];//存入地图 
int a[10][10];//表示棋盘 
int book[10];//标记棋子的数组 
int n,k,num;
void dfs(int h,int s)//h表示当前所在的行,s表示当前所摆放棋子的数目 
{
	if(s==k)//如果摆放数等于k 
	{
		num++;//方案数加1
		return ;
	}
	if(h>=n)//如果超出棋盘边界直接结束搜索 
		return ;
	for(int i=0;i<n;i++)
	{
		if(a[h][i]&&book[i]==0)//如果当前列没有摆放过棋子,并且当前位置可以摆放
		{
			book[i]=1;//先标记此位置 
			dfs(h+1,s+1);//搜索下一行 
			book[i]=0;//将标记清除 
		}
	}
	dfs(h+1,s);//如果当前行没有可以摆放的位置或者s已经等于k,但是还没有搜索完整个棋盘,将要继续搜索下一行
	return ;
}
int main()
{
	while(cin>>n>>k)
	{
		if(n==-1&&k==-1)
			break;
		num=0;
		memset(a,0,sizeof(a));
		memset(book,0,sizeof(book));
		for(int i=0;i<n;i++)
		{
			getchar();
			for(int j=0;j<n;j++)
			{
				cin>>map[i][j];
				if(map[i][j]=='#')
					a[i][j]=1;//标记可以摆放棋子的位置 
			}
		}
		dfs(0,0);
		cout<<num<<endl;
	}
	return 0;
}

 

Published 260 original articles · won praise 267 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43823808/article/details/103795791