| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 25147 | Accepted: 12424 |
Description
Input
Output
Sample Input
2 1 #. .# 4 4 ...# ..#. .#.. #... -1 -1
Sample Output
2 1
Source
解题思路:
类似于八皇后,只不过对于皇后的数目有了要求,八皇后中,一定要去皇后的数目==棋盘的维数,但是这里,棋子的个数!=棋盘的维数,所以,我们
要采用不同的方式来维护。
int x = pos/n;
int y = pos%n;
这在处理有关二维的dfs问题中,很常见,也很好用,通过这样的方法,我们就能控制每次棋子的移动位置,然后分别判断row[]和col[]和grid[][]来决定
是不是放棋子,如果能放入棋子的话,我们就说标记下->dfs->回溯。
代码:
# include<cstdio>
# include<iostream>
# include<algorithm>
# include<cstring>
# include<string>
# include<cmath>
# include<queue>
# include<stack>
# include<set>
# include<map>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
# define inf 999999999
# define MAX 10
int col[MAX];
int row[MAX];
char grid[MAX][MAX];
int n,k;
int ans;
void input()
{
getchar();
for ( int i = 0;i < n;i++ )
{
for ( int j = 0;j < n;j++ )
{
char ch = getchar();
if ( ch == ‘#‘ )
{
grid[i][j] = 1;
}
else
{
grid[i][j] = 0;
}
}
getchar();
}
}
void dfs( int pos,int step )
{
if ( step == k )
{
ans++;
return;
}
while ( pos < n*n )
{
int x = pos/n;
int y = pos%n;
if ( grid[x][y]==1&&col[y]==0&&row[x]==0 )
{//判断是否可以放棋子
row[x] = col[y] = 1;//对棋子所放的行和列做标记
dfs ( pos+1,step+1 );
row[x] = col[y] = 0;//解除标记,这样才能在新位置上放棋子
}
pos++;
}
}
int main(void)
{
while ( cin>>n>>k )
{
if ( n==-1&&k==-1 )
{
break;
}
memset(col,0,sizeof(col));
memset(row,0,sizeof(row));
input();
ans = 0;
dfs(0,0);
cout<<ans<<endl;
}
return 0;
}
代码:
原文:http://www.cnblogs.com/wikioibai/p/4382599.html