本题大意:给出一个n * m的地,‘#’ 代表草, ‘.’代表陆地,每次选择这片地里的两片草,可选相等的草,选择的两片草初始状态为被燃状态,每一分钟被点燃的草会将身边的四连块点。问你需要对于给定的这片地最少需要多少分钟能燃烧完,燃烧不完输出 -1.
本题思路:很直观的一道题,枚举所有可能开始燃烧的点,更新最小值就行,无法燃烧完则是输出-1。
参考代码:
1 //要勤于思考,思考使人明智,不要总是因为一两个点没有想到就浪费时间 2 #include <cstdio> 3 #include <queue> 4 #include <cmath> 5 #include <cstring> 6 #include <vector> 7 using namespace std; 8 9 struct node { 10 int x, y, step; 11 }now, Next; 12 13 const int maxn = 10 + 2, INF = 0x3f3f3f3f; 14 int n, m, t, ans, connected_block, maxstep, Case = 0; 15 char maze[maxn][maxn]; 16 bool vis_index[maxn][maxn]; 17 vector <node> grass; 18 19 bool check () { 20 for(int i = 0; i < n; i ++) 21 for(int j = 0; j < m; j ++) 22 if(maze[i][j] == '#' && !vis_index[i][j]) return false; 23 return true; 24 } 25 26 bool useful(int x, int y) { 27 return (x >= 0 && y >= 0 && x < n && y < m && maze[x][y] == '#' && !vis_index[x][y]); 28 } 29 30 void Init() { 31 grass.clear(); 32 memset(vis_index, false, sizeof vis_index); 33 ans = INF, connected_block = 0; 34 } 35 36 int bfs(node n1, node n2) { 37 queue < node> Q; 38 memset(vis_index, false, sizeof vis_index); 39 Q.push(n1), Q.push(n2); 40 maxstep = 0; 41 while(!Q.empty()) { 42 now = Q.front(); 43 Q.pop(); 44 if(vis_index[now.x][now.y]) continue; 45 maxstep = now.step; 46 vis_index[now.x][now.y] = true; 47 for(int dx = -1; dx <= 1; dx ++) { 48 for(int dy = -1; dy <= 1; dy ++) { 49 if(abs(dx - dy) == 1) { 50 if(useful(now.x + dx, now.y + dy)) { 51 Next.x = now.x + dx, Next.y = now.y + dy, Next.step = now.step + 1; 52 Q.push(Next); 53 } 54 } 55 } 56 } 57 } 58 return maxstep; 59 } 60 61 int main () { 62 scanf("%d", &t); 63 while(t --) { 64 Init(); 65 scanf("%d %d", &n, &m); 66 getchar(); 67 for(int i = 0; i < n; i ++) { 68 for(int j = 0; j < m; j ++) { 69 maze[i][j] =getchar(); 70 if(maze[i][j] == '#') { 71 node g; 72 g.x = i, g.y = j, g.step = 0; 73 grass.push_back(g); 74 } 75 } 76 getchar(); 77 } 78 //Find answer 79 for(int i = 0; i < grass.size(); i ++) 80 for(int j = i; j < grass.size(); j ++) { 81 grass[i].step = 0, grass[j].step = 0; 82 int temp = min(bfs(grass[i], grass[j]), ans); 83 if(check()) ans = min(temp, ans); 84 } 85 printf("Case %d: ", ++ Case); 86 if(ans == INF) printf("-1 "); 87 else printf("%d ", ans); 88 } 89 return 0; 90 }