N - Find a way

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

运用bfs来做,并且运用一个三维数组来区分两个人分别走过的踪迹

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=200+20;
const int INF=100000000;
char str[maxn][maxn];
int v[maxn][maxn][2];
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int n,m;
struct node{
	int x,y,op;
};
int bfs(node s,node q)
{
	queue<node> th;
	int minn=INF;
	th.push(s),th.push(q);
	v[s.x][s.y][s.op]=v[q.x][q.y][q.op]=1;
	while(!th.empty())
	{
		node rh=th.front();th.pop();
		if(str[rh.x][rh.y]=='@'&&v[rh.x][rh.y][0]&&v[rh.x][rh.y][1])
		minn=min(minn,v[rh.x][rh.y][0]+v[rh.x][rh.y][1]);
		for(int i=0;i<4;i++)
		{
			int x=rh.x,y=rh.y;
			x+=d[i][0];y+=d[i][1];
			if(x>=0&&x<n&&y>=0&&y<m&&str[x][y]!='#'&&v[x][y][rh.op]==0)//只要不是墙并且没有访问过 
			{
				v[x][y][rh.op]=v[rh.x][rh.y][rh.op]+1;
				node ths;
				ths.x=x,ths.y=y,ths.op=rh.op;
				th.push(ths);		
			}
		}
	}
	return minn-2;
}
int main()
{
	//freopen("N.txt","r",stdin);
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		node s,q;
		for(int i=0;i<n;i++)
		{
			scanf("%s",&str[i]);
			for(int j=0;j<m;j++)
			{
				if(str[i][j]=='Y')
				{
					s.x=i,s.y=j,s.op=0;
				}
				if(str[i][j]=='M')
				{
					q.x=i,q.y=j,q.op=1;
				}
			}
		}
		memset(v,0,sizeof(v));
		int ans=bfs(s,q);
		//cout<<ans<<endl;
		printf("%d\n",ans*11);
	}
	return 0;
 } 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值