J - Fire!

24 篇文章 0 订阅
14 篇文章 0 订阅

用先让火走的原则,再让人走,运用一个广搜即可,最后步骤不要忘了加一

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int INF=10000000;
const int maxn=1000+100;
int n,m;
char str[maxn][maxn];
int vis[maxn][maxn];
struct node{
	int x,y,step;
	node(){}
	node(int xx,int yy,int ss)
	{
		x=xx,y=yy,step=ss;
	}
};
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; 
queue<node> q;
int bfs()
{
	memset(vis,0,sizeof(vis));
	while(!q.empty())
	{
		node th=q.front();q.pop();
		int x=th.x,y=th.y,step=th.step;
		if(step!=INF&&(x==0||x==n-1||y==0||y==m-1))
			return step;
		for(int i=0;i<4;i++)
		{
			node rh=th;
			rh.x+=d[i][0],rh.y+=d[i][1];
			int xx=rh.x,yy=rh.y,sstep=rh.step;
			if(xx>=0&&xx<n&&yy>=0&&yy<m&&str[xx][yy]=='.')
			{
				if(sstep==INF)
				{
					str[xx][yy]='F';
					q.push(node(xx,yy,INF));
				}
				else if(!vis[xx][yy])
				{
					vis[xx][yy]=1;
					q.push((node(xx,yy,step+1)));
				}
			}
		}
	}
	return -1;
}
int main()
{
	int t;
	//freopen("J.txt","r",stdin);
	scanf("%d",&t);
	//cout<<t<<endl;
	while(t--)
	{
		while(!q.empty())	q.pop();
		scanf("%d %d",&n,&m);
		node star;
		int cnt=0;
		for(int i=0;i<n;i++)
		{
			scanf("%s",&str[i]);
			for(int j=0;str[i][j];j++)
			{
				if(str[i][j]=='J')
				{
					star.x=i,star.y=j,star.step=0;
				}
				if(str[i][j]=='F')
				{
					cnt++;
					q.push(node(i,j,INF));
				}
			}
		}
		q.push(star);
		int tmp=bfs();
		if(tmp==-1)	printf("IMPOSSIBLE\n");
		else	printf("%d\n",tmp+1);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值