bfs队列求最短路模板

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值