Codeforces Round #301 (Div. 2) C. Ice Cave(BFS)

来源:互联网 发布:linux内核优化 编辑:程序博客网 时间:2024/05/21 22:38

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

思路:从起始点走,每次走到一个‘.'点,则将其置为‘X'并加入队列,当搜索到节点为’X'且该节点为终点时,则成功抵达。若不存在,则无法到达。

#include<cstdio>#include<cstdlib>#include<queue>#include<cstring>#include<iostream>#include<algorithm>using namespace std;struct Node{    int x,y;};const int  dx[]={0,0,-1,1};const int dy[]={-1,1,0,0};int stx,sty,edx,edy,n,m;char g[550][550];queue<Node> q;int solve(){    g[stx][sty]='X';    Node tmp;    tmp.x=stx,tmp.y=sty;    q.push(tmp);    while(!q.empty())    {        Node now=q.front();        q.pop();        for(int i=0;i<4;i++)       {            int xx=now.x+dx[i];            int yy=now.y+dy[i];            if(xx>=1&&xx<=n&&yy>=1&&yy<=m)            {                 if(g[xx][yy]=='X')                 {                     if(xx==edx&&yy==edy) return 1;                     continue;                 }                 g[xx][yy]='X';                Node nt;                nt.x=xx,nt.y=yy;                q.push(nt);            }       }    }    return 0;}int main(){    scanf("%d%d",&n,&m);    getchar();    for(int i=1;i<=n;i++)    {        for(int j=1;j<=m;j++)          scanf("%c",&g[i][j]);        getchar();    }    scanf("%d%d",&stx,&sty);    scanf("%d%d",&edx,&edy);    if(solve()) printf("YES\n");    else printf("NO\n");    return 0;}


0 0
原创粉丝点击