Problem Description
给你T组数据,给你一个n,m的矩阵,.#分别代表空地,草丛。让你找两个草丛,开始烧,要求把所有的草都烧完,所需要最少的时间。烧一个草可以向上下左右扩散,扩散时间+1.
代码:找到所有草地下标。两两遍历所有的草丛,求出最小
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
struct node
{
int x, y;
};
vector<node> a;//存#的下标
char Map[15][15];
int vis[15][15], n, m, ans, sum;//标记&&路径,行,列,结果,每次BFS的结果。
int X[5] = {0, 1, 0, -1};//各个方向
int Y[5] = {-1, 0, 1, 0};
queue<node> q;
int judge(int x1, int y1)//判断能不能烧
{
if(x1 >= 0 && y1 >= 0 && x1 < n && y1 < m && Map[x1][y1] == '#' && !vis[x1][y1])
{
return 1;
}
else return 0;
}
void BFS(node u, node v)
{
int i, j;
memset(vis, 0, sizeof(vis));
q.push(u); q.push(v);
vis[u.x][u.y] = 1; vis[v.x][v.y] = 1;//初始化为1后面-1就好
node t, tem;
while(!q.empty())
{
t = q.front();
int xx = t.x, yy = t.y;
q.pop();
for(i = 0; i < 4; i++)
{
if(judge(X[i] + xx, Y[i] + yy))
{
vis[X[i] + xx][Y[i] + yy] = vis[xx][yy] + 1;
sum = max(sum, vis[xx][yy] + 1);
tem.x = X[i] + xx; tem.y = Y[i] + yy;
q.push(tem);
}
}
}
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(Map[i][j] == '#')
{
if(vis[i][j] == 0) break;
}
}
if(j != m) break;
}
if(i == n)
{
ans = min(ans, sum - 1);
}
}
int main()
{
int T, i, j, cas = 1;
scanf("%d", &T);
while(T--)
{
ans = 100;
scanf("%d %d", &n, &m);
for(i = 0; i < n; i++)
{
scanf("%s", Map[i]);
for(j = 0; j < m; j++)
{
if(Map[i][j] == '#')//找出所有的#
{
a.push_back((node){i,j});
}
}
}
for(i = 0; i < a.size(); i++)
{
for(j = i; j < a.size(); j++)//遍历所有草地的情况
{
sum = 1;
BFS(a[i], a[j]);
}
}
if(ans == 100) printf("Case %d: -1\n", cas++);
else
printf("Case %d: %d\n", cas++, ans);
a.clear();
}
}