#include <bits/stdc++.h>
using namespace std;
char mp[401][401];
int n,m,endx,endy;
struct node
{
int x,y;
int step;
bool operator < (const node &a) const {
return a.step < step;
}
};
int book[401][401];
priority_queue<node> que;
void DFS(int xx,int yy){
//行走方式
int next[4][2]={
{0,1},{1,0},{0,-1},{-1,0}
};//起点入队 计入记录
book[xx][yy]=1;
struct node np;
np.x=xx;
np.y=yy;
np.step=1;
que.push(np);
while(!que.empty()){
struct node k=que.top();
que.pop();
if((k.x==0||k.y==0||k.x==n-1||k.y==m-1)&&mp[k.x][k.y]=='D')
{cout<<k.step<<endl;
//到达终点 退出函数
return ;
}
for(int i=0;i<4;i++){
//点位+1
int nx=k.x+next[i][0];
int ny=k.y+next[i][1];
int step;
if(nx<0||nx>=n ||ny<0||ny>=m)
continue;//判断标记
if(mp[nx][ny]=='c')
{
step=k.step+1;
}
else if(mp[nx][ny]=='D') step=k.step;//判断边界
if(mp[nx][ny]!='#'&& book[nx][ny]==0){ //判断是否走过 判断是否障碍物
book[nx][ny]=1;//标记走过
struct node np;//创建点位
np.x=nx;
np.y=ny;
np.step=step;
que.push(np);//点位入队
}
}//一个点扩展完了出队
}
}
int main()
{
int x,y;
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%s",mp[i]);
}
scanf("%d%d",&x,&y);
DFS(x-1,y-1);
return 0;
}
bfs队列求最短路模板
最新推荐文章于 2022-09-22 14:44:24 发布