HDU 1312 red and black

来源:互联网 发布:java疯狂讲义第几版好 编辑:程序博客网 时间:2024/06/14 23:33

这题就是给你一个图,“@”代表人的位置,“#”代表不能走的地方,“.”代表能走的地方。能走的地方是联通的,让你统计一共有几个”.”。
裸搜索题,BFS或者DFS都行。提供两个版本。
BFS版

#include<cstdio>#include<cstring>#include<queue>using namespace std;int n,m,ans,ma[22][22],dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};struct point{    int x,y;};void BFS(int x,int y){    point a;    a.x=x;    a.y=y;    ma[x][y]=1;    queue<point> q;    q.push(a);    while(!q.empty())    {        point t=q.front();        q.pop();        for(int i=0;i<4;i++)        {            point l;            l.x=t.x+dir[i][0];            l.y=t.y+dir[i][1];            if(l.x>=0&&l.x<n&&l.y>=0&&l.y<m&&ma[l.x][l.y]==0)            {                ma[l.x][l.y]=1;                q.push(l);                ans++;            }        }    }}int main(){    int tx,ty;    while(scanf("%d%d",&m,&n)!=EOF)    {        getchar();        if(n==0&&m==0) break;        memset(ma,0,sizeof(ma));        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                char c;                scanf("%c",&c);                if(c=='#') ma[i][j]=1;                else if(c=='@')                {                    tx=i;                    ty=j;                }            }            getchar();        }        ans=1;        BFS(tx,ty);        printf("%d\n",ans);    }    return 0;}

DFS版

#include<cstdio>#include<cstring>#include<queue>using namespace std;int n,m,ans,ma[22][22],dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};struct point{    int x,y;};void DFS(int x,int y){    ans++;    point a;    a.x=x;    a.y=y;    ma[x][y]=1;    for(int i=0;i<4;i++)    {        point l;        l.x=x+dir[i][0];        l.y=y+dir[i][1];        if(l.x>=0&&l.x<n&&l.y>=0&&l.y<m&&ma[l.x][l.y]==0)            DFS(l.x,l.y);    }}int main(){    int tx,ty;    while(scanf("%d%d",&m,&n)!=EOF)    {        getchar();        if(n==0&&m==0) break;        memset(ma,0,sizeof(ma));        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                char c;                scanf("%c",&c);                if(c=='#') ma[i][j]=1;                else if(c=='@')                {                    tx=i;                    ty=j;                }            }            getchar();        }        ans=0;        DFS(tx,ty);        printf("%d\n",ans);    }    return 0;}
0 0
原创粉丝点击