bfs练习

#include <bits/stdc++.h>

using namespace  std;
const int N =1001;

char map1[N][N];
int visted[N][N];
int dirs[4][4] = {{-1,0},{1,0},{0,-1},{0,1}};
int n,m,xs,ys,xt,yt;
struct point{
    int x;
    int y;
    int step;

};
queue<point> que;

int main(int argc , char * argv[]){
//     freopen("/newhome/wangjd/leetcode/testin.txt","r",stdin);

    cin>>n>>m>>xs>>ys>>xt>>yt;
    for(int i = 1 ; i <=n ; ++i){
        for(int j = 1 ;j<=m; ++j){
            cin>>map1[i][j];
        }
    }
    point p;
    p.x=xs;
    p.y=ys;
    p.step=0;
    que.push(p);
    visted[xs][ys]=1;

    int flag = 0 ;
    while(!que.empty()){
        point temp = que.front();
        que.pop();
        if(temp.x==xt && temp.y == yt ){
            flag = 1;
            cout<<temp.step<<endl;
            break;
        }
        for(int i = 0 ; i <4;++i){
            int next_x = temp.x + dirs[i][0];
            int next_y = temp.y + dirs[i][1];
            if(next_x>=1 && next_x<= n && next_y >=1 && next_y<=m && map1[next_x][next_y]=='.'&& visted[next_x][next_y]==0){
                point new_temp;
                new_temp.x = next_x;
                new_temp.y = next_y;
                new_temp.step = temp.step+1;
                que.push(new_temp);
                visted[next_x][next_y]=1;
            }
        }
    }
    if(!flag){
        cout<<-1<<endl;
    }




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值