1 /* 2 题意:在一个矩阵里放炮台,满足行列最多只有一个炮台,除非有墙(X)相隔,问最多能放多少个炮台 3 搜索(DFS):数据小,4 * 4可以用DFS,从(0,0)开始出发,往(n-1,n-1)左下角走,x = cnt / n; y = cnt % n; 更新坐标, 4 直到所有点走完为止,因为从左边走到右边,只要判断当前点左上方是否满足条件就可以了 5 注意:当前点不能放炮台的情况也要考虑 6 g[x][y] == ‘o‘; 的错误半天才检查出来:) 7 */ 8 #include <cstdio> 9 #include <iostream> 10 #include <cstring> 11 #include <string> 12 #include <algorithm> 13 #include <map> 14 #include <cmath> 15 using namespace std; 16 17 const int MAXN = 1e4 + 10; 18 const int INF = 0x3f3f3f3f; 19 char g[5][5]; 20 int ans; 21 int n; 22 23 bool ok(int x, int y) 24 { 25 for (int i=y-1; i>=0; --i) 26 { 27 if (g[x][i] == ‘o‘) return false; 28 else if (g[x][i] == ‘X‘) break; 29 } 30 for (int i=x-1; i>=0; --i) 31 { 32 if (g[i][y] == ‘o‘) return false; 33 else if (g[i][y] == ‘X‘) break; 34 } 35 36 return true; 37 } 38 39 void DFS(int cnt, int tot) 40 { 41 if (cnt == n * n) 42 { 43 if (ans < tot) ans = tot; 44 return ; 45 } 46 47 else 48 { 49 int x = cnt / n; 50 int y = cnt % n; 51 52 if (g[x][y] == ‘.‘ && ok (x, y) == true) 53 { 54 g[x][y] = ‘o‘; 55 DFS (cnt+1, tot+1); 56 g[x][y] = ‘.‘; 57 } 58 59 DFS (cnt+1, tot); 60 } 61 } 62 63 int main(void) //ZOJ 1002/HDOJ 1045 Fire Net 64 { 65 //freopen ("ZOJ_1002.in", "r", stdin); 66 67 while (scanf ("%d", &n) == 1 && n) 68 { 69 for (int i=0; i<n; ++i) 70 scanf ("%s", &g[i]); 71 72 ans = -1; DFS (0, 0); 73 74 printf ("%d\n", ans); 75 } 76 77 return 0; 78 } 79 80 /* 81 5 82 1 83 5 84 2 85 4 86 */
时间: 2024-08-10 13:42:30