/* 这是一个测试程序。采用dfs产生所有4维下的测试用例。比较自己的算法和网上正解的算法。看自己的算法为什么错了 */ #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int countFires(int n,char city[][5]); int max(char city[][5],int n); bool canput(char map[5][5], int y, int x){ //判断能不能放塔 if(map[y][x] != '.')return 0; //以经放塔或者为墙。不能放塔 int i; for(i = y - 1; i >= 0; i--){ if(map[i][x] == 'X')break; //有一堵墙 if(map[i][x] == 'F')return 0; //以放塔 } for(i = x - 1; i >= 0; i--){ if(map[y][i] == 'X')break; if(map[y][i] == 'F')return 0; } return 1; } void dfs(char map[5][5], int n, int depth, int put, int &max){ if(put > max)max = put; if(depth >= n*n) //递归调了n*n次? return; dfs(map,n,depth+1,put,max); //这是最原始的地图,没有放任何塔 int y = depth / n, x = depth % n; //得到将要判断的点的x,y坐标 if(canput(map,y,x)){ map[y][x] = 'F'; put++; dfs(map, n, depth+1, put, max); //这是放了塔后的地图 map[y][x] = '.'; put--; } } void dfs_out(char city[][5],int n,int depth) { int firenet1 = 0; int firenet2 = 0; if(depth >= n * n) return; dfs_out(city,n,depth + 1); firenet1 = firenet2 = 0; dfs(city,n,0,0,firenet1); firenet2 = max(city,n); if(firenet1 != firenet2) { for(int i = 0;i < n;i++) { cout << city[i] << endl; } cout << firenet1 << "/t" << firenet2 << endl; } firenet1 = firenet2 = 0; int y = depth / n, x = depth % n; //得到将要判断的点的x,y坐标 city[y][x] = 'X'; dfs(city,n,0,0,firenet1); firenet2 = max(city,n); if(firenet1 != firenet2) { for(int i = 0;i < n;i++) { cout << city[i] << endl; } cout << firenet1 << "/t" << firenet2 << endl; } dfs_out(city,n,depth + 1); city[y][x] = '.'; } int main() { int n = 0; char city[5][5] = {'.','.','.','.',0 ,'.','.','.','.',0 ,'.','.','.','.',0 ,'.','.','.','.',0 ,'.','.','.','.',0}; dfs_out(city,4,0); return 0; } int max(char city[][5],int n) { int i = 0; int j = 0; int maxcount = 0; int temp = 0; char tempcity[4][5]; for(i = 0;i < n;i++) { for(j= 0;j < n;j++) { memcpy(tempcity,city,20); if('.' == tempcity[i][j]) { tempcity[i][j] = 1; temp = countFires(n,tempcity); if(temp > maxcount) maxcount = temp; } else { continue; } } } return maxcount; } int countFires(int n,char city[][5]) { int i = 0; int j = 0; int i1 = 0; int count = 1; int flag = 1; for(i = 0;i < n;i++) { for(j= 0;j < n;j++) { if('.' == city[i][j] ) { flag = 1; for(i1 = 0;i1 < j;i1++) { if('.' != city[i][i1] && 'X' != city[i][i1]) flag = 0; else if('X' == city[i][i1]) flag = 1; } if(!flag) continue; for(i1 = n -1;i1 > j;i1--) { if('.' != city[i][i1] && 'X' != city[i][i1]) flag = 0; else if('X' == city[i][i1]) flag = 1; } if(!flag) continue; for(i1 = 0;i1 < i;i1++) { if('.' !=city[i1][j] && 'X' != city[i1][j]) flag = 0; else if('X' == city[i1][j]) flag = 1; } if(!flag) continue; for(i1 = n -1;i1 > i;i1--) { if('.' !=city[i1][j] && 'X' != city[i1][j]) flag = 0; if('X' == city[i1][j]) flag = 1; } if(flag) { count ++; city[i][j] = count; } } } } return count; }