题意,10*10的地图,有若干块草地“#”,草地可以点燃,并在一秒后点燃相邻的草地。有墙壁‘·‘阻挡。初始可以从任意两点点火。问烧完最短的时间。若烧不完输出-1.
题解:由于100的数据量,直接暴力。枚举两个起点,推入队列,然后bfs。烧完就返回深度,更新一个min值。
坑:(帮同学照bug)
return t.step+1;bfs后没有算上最后一步
ac代码
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> #include <algorithm> #include <string.h> #include <queue> #include <vector> using namespace std; char map[15][15]; int vis[15][15]; int T, n, m, ans, num; struct Node { int i, j, step; Node(int i = 0, int j = 0, int step = 0) :i(i), j(j), step(step) {} }; int dir[4][2] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } }; bool check(int i, int j) { if (i<0 || i >= n || j<0 || j >= m || vis[i][j] || map[i][j] == '.') return true; return false; } int bfs(int i, int j, int x, int y) { queue<Node>q; q.push(Node(i, j, 0)); q.push(Node(x, y, 0)); vis[i][j] = 1; vis[x][y] = 1; int cnt; if (i == x&&j == y) cnt = 1; else cnt = 2; while (!q.empty()) { Node t = q.front(); q.pop(); for (int k = 0; k<4; k++) { int di = t.i + dir[k][0]; int dj = t.j + dir[k][1]; if (check(di, dj)) continue; q.push(Node(di, dj, t.step + 1)); vis[di][dj] = 1; cnt++; } if (cnt >= num) { //cout << i << ' ' << j << ' ' << x << ' ' << y <<' '<<t.step<< endl; return t.step+1; } } return -1; } int main() { scanf("%d", &T); for (int t = 1; t <= T; t++) { ans = (int)1e9; num = 0; scanf("%d%d", &n, &m); for (int i = 0; i<n; i++) { scanf("%s", map[i]); for (int j = 0; j<m; j++) if (map[i][j] == '#') num++; } if (num <= 2) { printf("Case %d: %d ", t, 0); continue; } for (int i = 0; i<n; i++) { for (int j = 0; j<m; j++) { if (map[i][j] != '#') continue; for (int x = 0; x<n; x++) { for (int y = 0; y<m; y++) { if (map[x][y] != '#') continue; memset(vis, 0, sizeof(vis)); int tmp = bfs(i, j, x, y); if (tmp>0) ans = min(ans, tmp); } } } } if (ans == (int)1e9) ans = -1; printf("Case %d: %d ", t, ans); } }