题解 LuoguP1746 【离开中山路】

非常裸的一道搜索题

个人不太喜欢写STL,比较喜欢手写数据结构,因为这样子会快(STL比手写会慢上许多)

对于手写队列,推广一下我的这篇博文(个人认为讲的还是挺详细的,而且实用)

好了,说正事,用BFS来做,也没有什么好注意的,直接上代码(C++)吧(代码里有注释):

#pragma GCC diagnostic error "-std=c++11"
#include <iostream>
#include <cstdio>
using namespace std;
template <class T>void r(T &a)//快读大法好 
{
    T s=0,w=1;a=0;char ch=getc(stdin);
    while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getc(stdin);}
    while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getc(stdin);}
    a=w*s;
}
template <class T,class... Y>void r(T& t,Y&... a){r(t);r(a...);}
int x1,y1,x2,y2,n;
int next[5][3]={{1,0},{0,1},{0,-1},{-1,0}};
struct note//用于存储队列元素 
{
    int x,y,t;
};
struct queue//手写队列大法好(速度比STL快) 
{
    int head=0,tail=0;
    note a[1000010];
    void pop(){head++;}
    void push(note num){a[tail]=num;tail++;}
    int size(){return tail-head;}
    note back(){return a[tail-1];}
    note front(){return a[head];}
    bool empty(){if(head==tail)return true;return false;}
};
bool m[1010][1010];
queue q;
void bfs()//bfs函数 
{
    r(n);//输入 
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        {
            char a;
            cin>>a;
            if(a=='1')m[i][j]=true;
        }
    r(x1,y1,x2,y2);
    m[x1][y1]=true;
    q.push({x1,y1,0});
    while(!q.empty())
    {
        int nx=q.front().x,ny=q.front().y,nt=q.front().t;
        for(int i=0;i<4;i++)
        {
            int tx=nx+next[i][0],ty=ny+next[i][1];
            if(tx<1||tx>n||ty<1||ty>n)continue;
            if(!m[tx][ty])
            {
                q.push({tx,ty,nt+1});
                m[tx][ty]=true;
                if(tx==x2&&ty==y2)
                {
                    cout<<nt+1;
                    return ;
                }
            }
        }
        q.pop();
    }
}
int main()//只有2行的主函数 
{
    bfs();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Naive-Cat/p/10664240.html