典型例題

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
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章