FZU Problem 2285 迷宫寻宝 BFS板子题

FZU Problem 2285 迷宫寻宝 BFS板子题

1.迷宫模型求最短路果断BFS
2.BFS搜索时,第一次找到即为最短路径,应该立即return
3.尽量用scanf,因为scanf比cin快

代码:

#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
using namespace std;
#define scan(n) scanf("%d",&n)
#define ll long long

int a[1010][1010];
int minnum=99999999;
int v[1010][1010];

struct cc
{
    int x,y;
    int num;
};
typedef struct cc pp;

int n;

void bfs(int i,int j)
{
    pp p;
    queue<pp> q;
    p.x=i;
    p.y=j;
    p.num=0;
    q.push(p);
    while(!q.empty())
    {
        p=q.front();
        q.pop();
        int x=p.x;
        int y=p.y;
        int num=p.num;
        v[x][y]=1;
        if(a[x][y]==2)
        {
            minnum=num;
            return;
        }
        pp t;
        if(x>1&&a[x-1][y]!=1&&v[x-1][y]==0)
        {
            t.x=x-1;
            t.y=y;
            t.num=num+1;
            v[x-1][y]=1;
            q.push(t);
        }
        if(x<n&&a[x+1][y]!=1&&v[x+1][y]==0)
        {
            t.x=x+1;
            t.y=y;
            t.num=num+1;
            v[x+1][y]=1;
            q.push(t);
        }
        if(y>1&&a[x][y-1]!=1&&v[x][y-1]==0)
        {
            t.x=x;
            t.y=y-1;
            t.num=num+1;
            v[x][y-1]=1;
            q.push(t);
        }
        if(y<n&&a[x][y+1]!=1&&v[x][y+1]==0)
        {
            t.x=x;
            t.y=y+1;
            t.num=num+1;
            v[x][y+1]=1;
            q.push(t);
        }
    }
    return;
}

int main()
{
    int i,j;
    int x,y;
    char cha[1010][1010];
    while(scan(n)!=EOF)
    {
        memset(v,0,sizeof(v));
        minnum=99999999;
        for(i=0;i<n;i++)
            scanf("%s",cha[i]);
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                char ch=cha[i-1][j-1];
                if(ch=='S')
                {
                    a[i][j]=1;
                    x=i;
                    y=j;
                }
                else if(ch=='E')
                    a[i][j]=2;
                else if(ch=='.')
                    a[i][j]=0;
                else
                    a[i][j]=1;
            }
        }
        bfs(x,y);
        if(minnum==99999999)
            cout<<-1<<endl;
        else
            cout<<minnum<<endl;
        }
    return 0;
}

你可能感兴趣的:(搜索)