典型例题

1,度小满的笔试题,寻找有障碍物的最短路径,第一行输入出发点坐标和障碍数,接下来输入各个障碍的坐标。求最短路径。

作者:henuzxy
链接:https://www.nowcoder.com/discuss/259953?type=post&order=time&pos=&page=1
来源:牛客网

#include<bits/stdc++.h>
 
using namespace std;
const int MAX = 1010;
const int ADD = 500;
const int xx[4] = {-1,0,1,0};
const int yy[4] = {0,-1,0,1};
class Node{
public:
    Node(int _x = 0,int _y = 0,int _step = 0){
        x = _x;
        y = _y;
        step = _step;
    }
    int x,y;
    int step;
};
bool book[MAX][MAX];
 
int px,py,N;
 
int pos(int x){
    return x+ADD;
}
int bfs(){
    Node Beg(0,0);
    queue<Node> que;
    que.push(Beg);
    book[Beg.x][Beg.y] = true;
 
    while(!que.empty()){
        Node v = que.front();que.pop();
        for(int i=0;i<4;++i){
            int nx = v.x + xx[i];
            int ny = v.y + yy[i];
            if(nx < -500 || nx > 500 || ny < -500 || ny > 500)
                continue;
            if(!book[pos(nx)][pos(ny)]){
             //   cout << nx << " " << ny << endl;
                book[pos(nx)][pos(ny)] = true;
                if(nx == px && ny == py)    return v.step+1;
                que.push(Node(nx,ny,v.step+1));
            }
        }
    }
    return -1;
}
int main(void){
    memset(book,false,sizeof(book));
    scanf("%d%d%d",&px,&py,&N);
    int x_i,y_i;
    for(int i=1;i<=N;++i){
        scanf("%d%d",&x_i,&y_i);
        book[pos(x_i)][pos(y_i)] = true;
    }
    cout << bfs() << endl;
 
    return 0;
}
/*
2 0 3
1 0
1 1
1 -1
*/

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值