1. 程式人生 > >POJ 1321 棋盤問題 題解

POJ 1321 棋盤問題 題解

棋盤問題

Time Limit: 1000MS  Memory Limit: 10000K

Total Submissions: 70224  Accepted: 33254

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

2
1

Source

蔡錯@pku ------------------------------------------------------------------------------------------------------------------------------------------------------
本題為一道典型的深搜的模板題 但剛開始見到的時候往往會找不到地方下手 博主的思路就是按照行進行深搜 然後標記給列 這樣就能保證不重複地遍歷所有元素 當然只有map上面是#的才能放咯 下面上我註釋仔細 誰都看的懂的程式碼 ------------------------------------------------------------------------------------------------------------------------------------------------------
 1
//Author:LanceYu 2 #include<iostream> 3 #include<string> 4 #include<cstring> 5 #include<cstdio> 6 #include<fstream> 7 #include<iosfwd> 8 #include<sstream> 9 #include<fstream> 10 #include<cwchar> 11 #include<iomanip> 12 #include<ostream> 13 #include<vector> 14 #include<cstdlib> 15 #include<queue> 16 #include<set> 17 #include<ctime> 18 #include<algorithm> 19 #include<complex> 20 #include<cmath> 21 #include<valarray> 22 #include<bitset> 23 #include<iterator> 24 #define ll long long 25 using namespace std; 26 const double clf=1e-8; 27 //const double e=2.718281828; 28 const double PI=3.141592653589793; 29 const int MMAX=2147483647; 30 //priority_queue<int>p; 31 //priority_queue<int,vector<int>,greater<int> >pq; 32 char map[9][9]; 33 int vis[9]; 34 int n,m,sum,num; 35 void dfs(int x)//按照行數搜尋 36 { 37 if(m==num)//如果做到了放入n個棋子,方案總數+1 38 { 39 sum++; 40 return; 41 } 42 if(x>n-1)//不能越界 43 return; 44 for(int j=0;j<n;j++) 45 { 46 if(!vis[j] && map[x][j]=='#')//如果這一層能放,就直接放進去,計數器+1 47 { 48 vis[j]=1;//縱軸標記,不能再次訪問 49 num++; 50 dfs(x+1); 51 num--; 52 vis[j]=0; 53 } 54 } 55 dfs(x+1); //如果這一行沒有,就直接進入下一行,繼續搜尋 56 } 57 int main() 58 { 59 while(scanf("%d%d",&n,&m)!=EOF) 60 { 61 if(n==-1&&m==-1) 62 return 0; 63 sum=0;num=0; 64 for(int i=0;i<n;i++) 65 scanf("%s",map[i]); 66 memset(vis,0,sizeof(vis)); 67 dfs(0); 68 printf("%d\n",sum); 69 } 70 71 return 0; 72 }

------------------------------------------------------------------------------------------------------------------------------------------------------

(不懂DFS的請點選連結)

Notes:主要是瞭解DFS演算法的本質

略微修改下模板即可AC

2018-11-20  01:46:50  Author:LanceYu