分析:首先,判断题目的草丛数,小于等于2的直接剪枝。
其次,枚举两堆草丛燃烧时间并记录最小值。
注意:燃烧事件应该以两个草丛中最长的为准。多于两个的直接-1。。
code:[718ms]
#include <cstdio>
#include <queue>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
typedef struct {
int x;
int y;
int wal;
}data;
data yihao,erhao;
data map_temp[105];
int n, m,cas, vis[15][15];
int dir[][2] = { {0,1} , {1,0} , {0,-1} , {-1,0} };
char grid[15][15];
void init()
{
memset(grid, 0, sizeof grid);
for (int i = 1; i <= n; i++)
scanf("%s", grid[i] + 1);
}
int bfs(int x1,int y1,int x2,int y2)
{
int ans = 0;
memset(vis, 0, sizeof vis);
vis[x1][y1] = 1;
vis[x2][y2] = 1;
yihao.x = x1, yihao.y = y1;
erhao.x = x2, erhao.y = y2;
yihao.wal = erhao.wal = 0;
queue <data> q;
q.push(yihao);
q.push(erhao);
while (q.size())
{
data now = q.front(); q.pop();
data nex;
if (ans < now.wal)
{
ans = now.wal;
}
for (int i = 0; i < 4; i++)
{
int a = now.x + dir[i][0], b = now.y + dir[i][1];
if (vis[a][b] == 0&&1<=a&&a<=n&&1<=b&&b<=m)
if(grid[a][b]=='#')
{
nex.x = a;
nex.y = b;
nex.wal = now.wal + 1;
q.push(nex);
vis[a][b] = 1;
}
}
}
return ans;
}
int cheack()
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(grid[i][j]=='#')
{
if(vis[i][j]==0)
{
return 0;
}
}
}
return 1;
}
void solve()
{
int ans = 1000000;
int cnt = 0;
for(int i=1;i<=n;i++)
for (int j = 1; j <= m; j++)
{
if (grid[i][j] == '#')
{
map_temp[cnt].x=i,map_temp[cnt++].y=j;
}
}
if (cnt <= 2)
{
printf("Case %d: 0\n", cas++);
return;
}
int temp;
for (int i = 0; i < cnt; i++)
{
for (int j = 0; j < cnt; j++)
{
if(i==j) continue;
temp=bfs(map_temp[i].x,map_temp[i].y,map_temp[j].x,map_temp[j].y);
if(cheack())
if(ans>temp)
ans=temp;
}
}
if(ans==1000000)
printf("Case %d: -1\n",cas++);
else
printf("Case %d: %d\n", cas++, ans);
}
int main(void)
{
cas = 1;
int t;
cin >> t;
while (t--)
{
scanf("%d %d",&n,&m);
init();
solve();
}
}
quesiton:双向bfs优化的实现..