Codeforces 540C Ice Cave (BFS)

题目:http://codeforces.com/problemset/problem/540/C

代码:

#include<stdio.h>
#include<string.h>
#include<queue>

using namespace std;

struct node
{
    int x,y;
} base,ans;

int n,m;
int dx[4]= {1,0,-1,0};
int dy[4]= {0,1,0,-1};
char maps[505][505];
int startx,starty;
int endx,endy;

int bfs(int x,int y)
{
    queue<node>q;
    base.x=x;
    base.y=y;

    q.push(base);
    //maps[base.x][base.y]='X';
    while(!q.empty())
    {
        ans=q.front();
        q.pop();

        for(int i=0; i<4; i++)
        {
            base.x=ans.x+dx[i];
            base.y=ans.y+dy[i];
            if(base.x>0&&base.x<=n&&base.y>0&&base.y<=m)
            {
                if(base.x==endx&&base.y==endy)                      //将判断条件放到下面。
                {
                    //printf("1 %d %d\n",base.x,base.y);
                    if(maps[base.x][base.y]=='X')
                    {
                        return 1;
                    }
                    else
                    {
                        maps[base.x][base.y]='X';
                        q.push(base);
                    }
                }
                else if(maps[base.x][base.y]!='X')
                {
                   // printf("2 %d %d\n",base.x,base.y);
                    maps[base.x][base.y]='X';
                    q.push(base);
                }
            }
        }
    }
    return 0;
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
        scanf("%s",maps[i]+1);

    scanf("%d%d%d%d",&startx,&starty,&endx,&endy);

    if(bfs(startx,starty))
        printf("YES\n");
    else
        printf("NO\n");

}


太笨了,搜索的一点变形就做不出来呀。

你可能感兴趣的:(Codeforces 540C Ice Cave (BFS))