標籤:
棋盤問題
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 27072 |
|
Accepted: 13392 |
Description
在一個給定形狀的棋盤(形狀可能是不規則的)上面擺放棋子,棋子沒有區別。要求擺放時任意的兩個棋子不能放在棋盤中的同一行或者同一列,請編程求解對於給定形狀和大小的棋盤,擺放k個棋子的所有可行的擺放方案C。
Input
輸入含有多組測試資料。
每組資料的第一行是兩個正整數,n k,用一個空格隔開,表示了將在一個n*n的矩陣內描述棋盤,以及擺放棋子的數目。 n <= 8 , k <= n
當為-1 -1時表示輸入結束。
隨後的n行描述了棋盤的形狀:每行有n個字元,其中 # 表示棋盤地區, . 表示空白地區(資料保證不出現多餘的空白行或者空白列)。
Output
對於每一組資料,給出一行輸出,輸出擺放的方案數目C (資料保證C<2^31)。
Sample Input
2 1#..#4 4...#..#..#..#...-1 -1
Sample Output
21
Source
蔡錯@pku
1 //num個棋盤空位,k個棋子,其實就是八皇后問題的變形。空位一個一個去填補,但要注意順序。 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <queue> 6 #include <stack> 7 #include <iostream> 8 using namespace std; 9 char map[10][10];10 bool col[10],row[10];11 struct node{12 int x,y;13 };14 node m[65];15 int sum,k,n,num;16 void dfs(int num1){17 int x=m[num1].x;18 int y=m[num1].y;19 if(row[x]||col[y]){20 return;21 }22 row[x]=true;//回溯23 col[y]=true;24 k--;25 if(!k){26 sum++;27 }28 else{29 int i;30 for(i=num1+1;i<num;i++){31 dfs(i);32 }33 }34 k++;35 row[x]=false;36 col[y]=false;37 }38 int main(){39 //freopen("D:\\INPUT.txt","r",stdin);40 while(scanf("%d %d",&n,&k)!=EOF){41 if(n==-1&&k==-1){42 break;43 }44 memset(col,false,sizeof(col));45 memset(row,false,sizeof(row));46 int i,j;47 num=0;48 sum=0;49 for(i=0;i<n;i++){50 for(j=0;j<n;j++){51 cin>>map[i][j];52 if(map[i][j]==‘#‘){53 m[num].x=i;54 m[num++].y=j;55 }56 }57 }58 for(i=0;num-i>=k;i++){59 dfs(i);60 }61 //cout<<sum<<endl;62 cout<<sum<<endl;63 }64 return 0;65 }
poj 1321 棋盤問題