BFS(广搜,啊哈算法,模板)

啊哈算法版: 

#include<iostream>
#include<algorithm>
#include<stack>
#include<set>
#include<queue>
#include<map>
#include<string>
#include<cstring>
#include<vector>
#include<ctype.h>
#include<sstream>
#include<unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
struct node
{
    int x,y;
    int s;
    int f;//父亲在队列中的编号。???干啥用的呢?有点像课本上的那个呀。
};
node que[2501];
int head,tail;
//mmp数组表示地图
int mmp[51][51];
//Book数组用来记录哪些点已经在队列中,防止一个点被重复扩展.....为啥教材上没有呢?
int Book[51][51];
//定义一个用于表示走的方向的数组
int Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};

int main()
{

    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        cin>>mmp[i][j];
    int startx,starty,p,q;
    cin>>startx>>starty>>p>>q;
    head=tail=1;
    que[tail].x=startx;
    que[tail].y=starty;
    que[tail].f=0;
    que[tail].s=0;
    tail++;
    Book[startx][starty]=1;
    int flag=0;
    while(head<tail)
    {
        int tx,ty;
        for(int i=0;i<3;i++)
        {
            tx=que[head].x+Next[i][0];
            ty=que[head].y+Next[i][1];
            if(tx<1||ty<1||tx>n||ty>m) continue;
            if(Book[tx][ty]==0&&mmp[tx][ty]==0)
            {
                que[tail].x=tx;
                que[tail].y=ty;
                tail++;
                Book[tx][ty]=1;
                mmp[tx][ty]=1;
            }

        }
        if(que[head].x==p&&que[head].y==q)
        {
            flag=1;
            break;
        }
        head++;

    }
    if(flag==1) cout<<que[head].x<<" "<<que[head].y<<endl;
    return 0;


}

/*
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
*/



广搜的知识点寒假的时候再整理吧,有段时间没用广搜了,时间长了不记好笔记的话就容易忘掉知识。(19年11月28日)


发布了77 篇原创文章 · 获赞 11 · 访问量 5004

猜你喜欢

转载自blog.csdn.net/qq_43346054/article/details/101461273