poj-1321-棋盘问题

Description:

Input

Output

Sample Input

2 1

#.
.#
4 4
…#
..#.
.#..

#…
-1 -1
Sample Output

2
1

To solve this problem,you should clear about the judge conditions——Each line and each column cannot have a piece at the same time.

Click to see Chinese Intentional analysis 这道题跟八皇后很像，就是判断条件不太一样，每一行和每一列不能同时有棋子，具体看代码注释。

Code:

#include<iostream>
#include<cstring>
using namespace std;
char s[10][10];//The map
int flag[10];//Record whether a column has been put on the chess piece
int n,k,ans,anss;//anss represents how many pieces have been placed now.ans is the final answer.
void dfs(int now)
{
if(k==anss)//All the pieces are finished.
{
ans++;
return ;
}
if(now>=n)//Boundary conditions
return ;
for(int j=0;j<n;j++)
{
if(flag[j]==0&&s[now][j]=='#')//Judge whether you can put down the pieces here.
{
flag[j]=1;
anss++;
dfs(now+1);
flag[j]=0;//For the back
anss--;
}
}
dfs(now+1);
}
int main()
{
while(cin>>n>>k)
{
memset(s,0,sizeof(s));
ans=0;
if(n==-1&&k==-1)
break;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>s[i][j];
dfs(0);
cout<<ans<<endl;
}
return 0;
}
Click to see Chinese code ` #include #include using namespace std; char s[10][10];//存起来的图 int flag[10];//标记这一列已经放过棋子 int n,k,ans,anss;//anss是现在已经放上去的棋子，ans是最后的答案 void dfs(int now) { if(k==anss) { ans++; return ; } if(now>=n) return ; for(int j=0;j>n>>k) { memset(s,0,sizeof(s)); ans=0; if(n==-1&&k==-1) break; for(int i=0;i>s[i][j]; dfs(0); cout<