POJ 1321 棋盘问题

解题思路:DFS

代码
   
     
#include < iostream >
using namespace std;
char chess[ 8 ][ 9 ];
int n, m;
inline
bool IsOk( int i, int j)
{
int k; bool istrue = true ;
for (k = 0 ;k < i && istrue;k ++ )
if (chess[k][j] == ' * ' )istrue = false ;
return istrue;
}
int DFS( int layer, int k)
{
if (k == 0 ) return 1 ;
if (n - layer + 1 < k) return 0 ;
int i,d = 0 ;
for (i = 0 ;i < n;i ++ )
{
if (chess[layer - 1 ][i] == ' # ' && IsOk(layer - 1 , i))
{
chess[layer
- 1 ][i] = ' * ' ;
d
+= DFS(layer + 1 ,k - 1 );
chess[layer
- 1 ][i] = ' # ' ;
}
}
d
+= DFS(layer + 1 , k);
return d;
}

int main()
{
int i, ans;
while (scanf( " %d %d " , & n, & m) && ! (n ==- 1 && m ==- 1 ))
{
for (ans = i = 0 ;i < n;i ++ )scanf( " %s " ,chess[i]);
ans
= DFS( 1 , m);
printf(
" %d\n " , ans);
}
return 0 ;
}

 

你可能感兴趣的:(poj)