http://poj.org/problem?id=1321
思路:按行搜索,回溯时还原棋盘。
1 #include <stdio.h> 2 #include <string.h> 3 int map[9][9],vis[9]; 4 int ans,n,k; 5 void dfs(int row,int cnt) 6 { 7 8 if (k==cnt) 9 { 10 ans++; 11 return ; 12 } 13 if (row > n) 14 return ; 15 for (int i = 1; i <= n; i ++) 16 { 17 if (map[row][i] && !vis[i]) 18 { 19 vis[i] = 1; 20 dfs(row+1,cnt+1); 21 vis[i] = 0; 22 } 23 } 24 dfs(row+1,cnt);//处理k<n的情况 25 return ; 26 } 27 int main() 28 { 29 while(~scanf("%d%d%*c",&n,&k)) 30 { 31 if (n==-1&&k==-1) 32 break; 33 char ch; 34 ans = 0; 35 memset(map,0,sizeof(map)); 36 memset(vis,0,sizeof(vis)); 37 for (int i = 1; i <= n; i ++) 38 { 39 for (int j = 1; j <= n; j ++) 40 { 41 scanf("%c",&ch); 42 if (ch=='#') 43 map[i][j] = 1; 44 } 45 getchar(); 46 } 47 dfs(1,0); 48 printf("%d ",ans); 49 } 50 return 0; 51 }