#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;
}
计蒜客 蒜头君回家 BFS
最新推荐文章于 2022-03-29 12:00:58 发布