poj 2157 Maze

   bfs.
   先找小写字母,标记每种小写原来总共的exsit[], 能过搜到的小写字母用f[]标记,搜到一个,就加一,如果搜到的是大写字母,判断f[]>exsit[] 如果是,入队,如果不是,先保存起来,之后每次判断一下,如果满足f[]>exsit[]就入队。如果搜到‘G’结束搜索,得出答案。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char s[25][25];
int f[5],exsit[5];
int sx,sy,n,m;
int vis[25][25];
int go[][2]={-1,0,1,0,0,1,0,-1},flag=0,num=0;
struct array
{
    int x,y;
};
struct xy
{
    int xx,yy,t,panduan;
}rt[405];
int bfs1()
{
    int i,j,aa,bb;
    queue<array>M;
    array temp,next;
    temp.x=sx;temp.y=sy;
    vis[sx][sy]=1;
    M.push(temp);
    while(!M.empty())
    {
        temp = M.front();
        M.pop();
        for(i=0;i<num;i++)
        {
            if(rt[i].panduan==0)
            {
                j=rt[i].t;
                if(f[j]>=exsit[j])
                {
                    next.x=rt[i].xx;next.y=rt[i].yy;
                    M.push(next);
                    rt[i].panduan=1;
                }
            }
        }
        for(i=0;i<4;i++)
        {
            aa=temp.x+go[i][0];
            bb=temp.y+go[i][1];
            if(aa>=0&&aa<n&&bb>=0&&bb<m&&s[aa][bb]!='X'&&vis[aa][bb]==0)
            {
                next.x=aa;next.y=bb;
                if(s[aa][bb]=='G')
                {
                    //cout<<temp.x<<" () "<<temp.y<<endl;
                    flag=1;return 0;
                }
                if(s[aa][bb]<'A'||s[aa][bb]>'E')
                {
                    vis[aa][bb]=1;
                    if(s[aa][bb]>='a'&&s[aa][bb]<='e')
                    {
                        j=s[aa][bb]-'a';
                        f[j]++;
                    }
                    M.push(next);
                }
                if(s[aa][bb]>='A'&&s[aa][bb]<='E')
                {
                    j=s[aa][bb]-'A';
                    if(f[j]>=exsit[j])
                    {
                        next.x=aa;next.y=bb;
                        vis[aa][bb]=1;
                        M.push(next);
                    }
                    else
                    {
                        rt[num].xx=aa;rt[num].yy=bb;
                        rt[num].t=j;rt[num].panduan=0;num++;
                    }
                }
            }
        }
    }
}
int main()
{
    int i,j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0)break;
        for(i=0;i<5;i++)
        {
            exsit[i]=0;f[i]=0;
        }
        num=0;
        for(i=0;i<n;i++)
        {
            scanf("%s",s[i]);
            for(j=0;j<m;j++)
            {
                vis[i][j]=0;
                if(s[i][j]=='S')
                  sx=i,sy=j;
                if(s[i][j]>='a'&&s[i][j]<='e')
                 exsit[s[i][j]-'a']++;
            }
        }
        flag=0;
        bfs1();
        if(flag)
          printf("YES\n");
        else printf("NO\n");
    }
}

你可能感兴趣的:(bfs)