题目:戳此进入
题意:#为草堆,.为土地,题目要求找到两个草堆点燃,点燃的草堆每秒会向四周扩散燃烧,只有相连的草堆才能被引燃,判断能否点燃地图中的全部草堆,如果能需要的最短时间,初始时间为0秒。
分析:使用双BFS,找到符合条件的两个点,同时压入队列,进行广搜,因为地图最大是10*10,因此可以遍历所有条件,时间复杂度可以满足。(要考虑点燃同一个草堆的情况,当时因为没有考虑WA了很多遍)
#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define inf 0X3f3f3f3f
int n, m, ans;
int f[4][2] = { 1,0,0,1,-1,0,0,-1 };
char mp[15][15];
int vis[15][15];
struct node
{
int x, y, cnt;
friend bool operator< (node n1, node n2)
{
return n1.cnt > n2.cnt; //"<"为从大到小排列,">"为从小到大排列
}
} now, Next;
void bfs(int x, int y, int x1, int y1)
{
int sum = 0;
memset(vis, 0, sizeof vis);
priority_queue<node>p;
vis[x][y] = 1;
vis[x1][y1] = 1;
now.x = x;
now.y = y;
now.cnt = 0;
p.push(now);
now.x = x1;
now.y = y1;
now.cnt = 0;
p.push(now);
while (p.size())
{
int tx, ty;
now = p.top();
p.pop();
for (int i = 0; i < 4; i++)
{
tx = now.x + f[i][0];
ty = now.y + f[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && mp[tx][ty] == '#' && vis[tx][ty] == 0)
{
vis[tx][ty] = 1;
Next.x = tx;
Next.y = ty;
Next.cnt = now.cnt + 1;
sum = max(Next.cnt, sum);
p.push(Next);
}
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
if (mp[i][j] == '#' && vis[i][j] == 0)
return;
}
ans = min(ans, sum);
return;
}
int main()
{
int t, cas = 1;
cin >> t;
while (t--)
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
cin >> mp[i];
}
ans = inf;
int flag = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (mp[i][j] == '#')
{
flag++;
for (int i1 = i; i1 < n; i1++)
{
for (int j1 = 0; j1 < m; j1++)
{
if (i1 == i && j1 <j)
continue;
if (mp[i1][j1] == '#')
bfs(i, j, i1, j1);
flag++;
}
}
}
}
}
if (flag == 1)
ans = 0;
if (ans == inf)
ans = -1;
cout << "Case " << cas++ << ": " << ans << endl;
}
return 0;
}