题目链接:点击打开链接
题意
有一个n*m的草地和空地,#表示草地,其中只有草地能被点着,可以任选两块草地进行点着,每块烧着的草地在1s后会延伸到上下左右的格子,问烧完所有格子需要多少时间。如果不能烧完,输出-1.
题解
采用双路BFS的思想,每次加入两个点进行BFS,然后判断条件(这些都是模板),这里要进行多次BFS,即每次烧的两块草地不一样,取最小值。。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<vector>
using namespace std;
const int INF = 1e5;
const int maxn = 20;
struct node{
int x,y,tot;
};
int t,n,m,ans=INF;
char s[maxn][maxn];
bool vis[maxn][maxn];
vector<node> g;
void init()
{
memset(vis,0,sizeof(vis));
memset(s,0,sizeof(s));
ans = INF;
g.clear();
}
bool check(int x,int y)
{
if(s[x][y]=='#'&&!vis[x][y]&&x>=0&&x<n&&y>=0&&y<m)
return true;
return false;
}
bool judge()
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(s[i][j]=='#'&&!vis[i][j])
return false;
}
return true;
}
int bfs(node n1,node n2)
{
queue<node> q;
memset(vis,0,sizeof(vis));
q.push(n1);
q.push(n2);
int depth = 0;//当前的值
while(!q.empty())
{
node a = q.front();
q.pop();
if(vis[a.x][a.y]) continue;
depth = a.tot;
vis[a.x][a.y] = 1;
if(check(a.x-1,a.y))
{
node next;
next.x = a.x-1;
next.y = a.y;
next.tot = a.tot+1;
q.push(next);
}
if(check(a.x+1,a.y))
{
node next;
next.x = a.x+1;
next.y = a.y;
next.tot = a.tot+1;
q.push(next);
}
if(check(a.x,a.y+1))
{
node next;
next.x = a.x;
next.y = a.y+1;
next.tot = a.tot+1;
q.push(next);
}
if(check(a.x,a.y-1))
{
node next;
next.x = a.x;
next.y = a.y-1;
next.tot = a.tot+1;
q.push(next);
}
}
// for(int i=0;i<n;i++)
// {
// for(int j=0;j<n;j++)
// cout<<vis[i][j]<<" ";
// cout<<endl;
// }
if(judge()) {
return depth;
}
return INF;
}
int main()
{
// freopen("d://test.txt","r",stdin);
cin>>t;
for(int cnt=1;cnt<=t;cnt++)
{
init();
cin>>n>>m;
for(int i=0;i<n;i++)
scanf("%s", &s[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(s[i][j]=='#') {
node a;
a.x = i;
a.y = j;
a.tot = 0;
g.push_back(a);//采用vector,符合条件的push进去
}
int len = g.size();
for(int i=0;i<len;i++)//对符合条件的进行遍历,每次bfs两个,注意不重复
for(int j=i;j<len;j++)
{
ans = min(bfs(g[i],g[j]),ans);
}
printf("Case %d: ",cnt);
if(ans==INF) cout<<"-1"<<endl;
else cout<<ans<<endl;
}
return 0;
}