HDU 1312 red and black

这题就是给你一个图,“@”代表人的位置,“#”代表不能走的地方,“.”代表能走的地方。能走的地方是联通的,让你统计一共有几个”.”。
裸搜索题,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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值