烧火游戏(双向BFS)

题目链接:点击打开链接

题意

有一个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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

总想玩世不恭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值