棋盤問題
Descriptions:
在一個給定形狀的棋盤(形狀可能是不規則的)上面擺放棋子,棋子沒有區別。要求擺放時任意的兩個棋子不能放在棋盤中的同一行或者同一列,請編程求解對於給定形狀和大小的棋盤,擺放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
2
1
題目鏈接:
https://vjudge.net/problem/POJ-1321
AC代碼:
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> #define mod 1000000007 #define ll long long #define INF 0x3f3f3f3f using namespace std; char mp[15][15]; int vis[15];//列 int n,k; int sum=0; void dfs(int x,int cnt)//x為當前行,cnt為當前擺放的棋子數 { if(cnt==k) { sum++; } for(int i=x; i<n; i++) { for(int j=0; j<n; j++) { if(mp[i][j]=='#'&&vis[j]==0)//判斷這一列沒有走過 { vis[j]=1; dfs(i+1,cnt+1); vis[j]=0; } } } } int main() { while(cin >> n >>k) { if(n==-1&&k==-1) break; else { //每次都要更新 sum=0; memset(vis,0,sizeof(vis)); for(int i=0; i<n; i++) for(int j=0; j<n; j++) cin >> mp[i][j]; dfs(0,0); } cout<<sum<<endl; } }