FZU Problem 2285 Maze Treasure Hunting BFS Board Problem

FZU Problem 2285 Maze Treasure Hunting BFS Board Problem

1. Find the shortest path and decisive BFS for the maze model
2. When searching for BFS , the shortest path is the first time you find it, you should return immediately
3. Try to use scanf, because scanf is faster than cin

Code:

#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;
}

Guess you like

Origin blog.csdn.net/qq_40534166/article/details/88932260