计蒜客 蒜头君回家 BFS

#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m;
char Map[2010][2010];
bool inq1[2010][2010] = {false};
bool inq2[2010][2010] = {false};
int X[4] = {0,0,-1,1};
int Y[4] = {1,-1,0,0};
struct node{
	int x,y,step = 0;
	bool key;
}Node;
int BFS1(int x,int y){//从(x,y)抵达P的最短路径 
	queue<node> q;
	Node.x = x;
	Node.y = y;
	Node.step = 0;
	Node.key = false;
	inq1[Node.x][Node.y] = true;
	q.push(Node);
	while(!q.empty()){
		node top = q.front();
		q.pop();
		for(int i =0;i<4;i++){
			Node.x = top.x + X[i];
			Node.y = top.y + Y[i]; 
			if(Node.x>=0&&Node.x<n&&Node.y>=0&&Node.y<m&&Map[Node.x][Node.y]!='#'&&((top.key&&inq2[Node.x][Node.y]==false)||inq1[Node.x][Node.y]==false)){
				Node.step = top.step + 1;
				Node.key = top.key;
				if(Map[Node.x][Node.y] =='P'||top.key){
					Node.key = true;
					inq2[Node.x][Node.y] = true;
				}
				if(Map[Node.x][Node.y] =='T'&&Node.key){
					return Node.step;
				}
				q.push(Node);
				//cout<<Node.x<<" "<<Node.y<<" "<<Map[Node.x][Node.y]<<" "<<Node.step<<'\n';
				inq1[Node.x][Node.y] = true;	
				}
		}
	}
	return 0;
}
int main(){
	//freopen("in.txt","r",stdin);
	cin>>n>>m;
	int sx;
	int sy;
	for(int i = 0;i<n;i++){
		for(int j =0;j<m;j++){
			cin>>Map[i][j];
			if(Map[i][j]=='S'){
				sx = i;
				sy = j; 
			}
		}
	}
	cout<<BFS1(sx,sy)<<'\n';
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xiu_cs

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

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

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

打赏作者

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

抵扣说明:

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

余额充值