poj 2386 poj1562 poj1979 图的遍历 八个方向和四个方向 深搜

60 篇文章 0 订阅
三个题基本上就是一样的思路,学到了怎么遍历四个方向和八个方向

count初始化 poj1562

#include<stdio.h>
#include<string.h>
int w,h;
char a[105][105];

void mi_gong(int x,int y)
{

    a[x][y]='*';

    int tempx;
    int tempy;
    for(int k=-1;k<=1;k++)
    {
        for(int p=-1;p<=1;p++)
        {
            tempx=x+k;
            tempy=y+p;
            if(tempx>=0&&tempy>=0&&tempx<h&&tempy<w&&a[tempx][tempy]=='@')
                mi_gong(tempx,tempy);
        }
    }
    return ;
}

int main()
{
    
    while(scanf("%d%d",&h,&w),h||w)
    {
        int count=0;
        //memset(a,'*',sizeof(a));
        getchar();      
        for(int i=0;i<h;i++)
        {
            scanf("%s",a[i]);
            getchar();
        }

        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++)
            {
                if(a[i][j]=='@')
                {
                    mi_gong(i,j);
                    count++;
                }
            }
        }
        printf("%d\n",count);
    }
    return 0;
}


poj2386
#include<stdio.h>

int w,h;
char a[105][105];

void mi_gong(int x,int y)
{

    a[x][y]='.';

    int tempx;
    int tempy;
    for(int k=-1;k<=1;k++)
    {
        for(int p=-1;p<=1;p++)
        {
            tempx=x+k;
            tempy=y+p;
            if(tempx>=0&&tempy>=0&&tempx<h&&tempy<w&&a[tempx][tempy]=='W')
                mi_gong(tempx,tempy);
        }
    }
    return ;
}

int main()
{
    int count=0;
    scanf("%d%d",&h,&w);

    getchar();
    for(int i=0;i<h;i++)
    {
        scanf("%s",a[i]);
        getchar();
    }

    for(int i=0;i<h;i++)
    {
        for(int j=0;j<w;j++)
        {
            if(a[i][j]=='W')
            {
                mi_gong(i,j);
                count++;
            }
        }
    }

    printf("%d",count);
    return 0;
}


poj1979
#include<stdio.h>
#include<iostream>
using namespace std;

int w,h;
char a[21][21];

int mi_gong(int x,int y)
{
    if(x<0||x>=h||y<0||y>=w)
        return 0;
    if(a[x][y]=='#')
        return 0;
    a[x][y]='#';
    return (1+mi_gong(x-1,y)+mi_gong(x,y-1)+mi_gong(x+1,y)+mi_gong(x,y+1));
}

int main()
{
    int kw,kh;
    while(scanf("%d%d",&w,&h),w||h)
    {
        getchar();
        for(int i=0;i<h;i++)
        {
            scanf("%s",a[i]);
            getchar();
        }
        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++)
            {
                if(a[i][j]=='@')
                {
                    printf("%d\n",mi_gong(i,j));
                    break;
                }
            }
        }
    }


    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值