Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 59097 | Accepted: 28382 |
Description
Input
每組數據的第一行是兩個正整數,n k,用一個空格隔開,表示了將在一個n*n的矩陣內描述棋盤,以及擺放棋子的數目。 n <= 8 , k <= n
當爲-1 -1時表示輸入結束。
隨後的n行描述了棋盤的形狀:每行有n個字符,其中 # 表示棋盤區域, . 表示空白區域(數據保證不出現多餘的空白行或者空白列)。
Output
Sample Input
2 1 #. .# 4 4 ...# ..#. .#.. #... -1 -1
Sample Output
2 1
題目大意:
輸入n,k,再輸入n階矩陣。在n*n的棋盤格子上放入k個棋子(棋子之間沒有區別),要求在不同行不同列,且棋子只能在#位置放,
求出所有的方案數。
分析:題目要求不同行不同列,就沒必要按照之前的搜索圖的方法挨個位置查找,比較費時也可能不好查找。我們只要在一行找到一個,然後換下一行繼續找就可以,找完所有的之後再回溯查找別的方案,找到全部的方案數。
代碼:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,k;
int num ,step;
char str[10][10];
int book[10];
void dfs(int x)
{
if(step == k) //已經放下了k個棋子,方案數加1
{
num++;
return ;
}
if(x >= n) //搜完所有的行
return ;
for(int j=0;j<n;j++) //列
{
if(book[j] == 0 && str[x][j] == '#') //第j列還沒有被找過,並且該位置是#棋盤。
{
book[j] = 1; //之後不能再找這一列了
step ++; //放下一個棋子
dfs(x+1); //在這一行的某一列中有‘#’,直接轉到下一行
book[j] = 0; //取消標記方便下一次查找不同的方案
step--;
}
}
dfs(x+1); //如果上一行的每列都沒有‘#’,則換到下一行
return ;
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF) //多組測試數據輸入
{
num = 0;step = 0;
if(n == -1 && k == -1) //結束輸入的標誌
break;
memset(book,0,sizeof(book));
for(int i=0;i<n;i++)
scanf("%s",str[i]);
//按照行與列搜索而不是挨個位置搜索
dfs(0); //一行一行搜索
printf("%d\n",num);
}
return 0;
}
Java代碼:
import java.util.*;
public class Main {
static int n,k;
static int book[] = new int[10];
static char[][] s = new char[10][10];
static int num,step;
public static void dfs(int x) {
if(step == k)
{
num++;
return ;
}
if(x >= n)
return ;
for(int j=0;j<n;j++)
{
if(book[j] == 0 && s[x][j] == '#')
{
book[j] = 1;
step++;
dfs(x+1);
book[j] = 0;
step--;
}
}
dfs(x+1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String str = new String();
while(in.hasNext())
{
n = in.nextInt();
k = in.nextInt();
if(n == -1 && k == -1)
break;
Arrays.fill(book, 0);
num = 0;
step = 0;
for(int i=0;i<n;i++)
{
str = in.next(); //輸入一行字符串
for(int j=0;j<n;j++)
{
s[i][j] = str.charAt(j); //轉換成二維數組
}
}
dfs(0);
System.out.println(num);
//for(int i=0;i<n;i++)
//{
//for(int j=0;j<n;j++)
//System.out.print(s[i][j]);
//System.out.println();
//}
}
}
}