aoj0118

一、题意:有三种水果分别用,'@','*','#'三种符号表示,上下左右相连的同种水果被看做是一个区域,问一共有多少个区域

二、思路:用dfs去标记相连区域,然后遍历每个没有被标记的位置进行dfs

三、代码:

#include"iostream"
#include"stdio.h"
#include"vector"
using namespace std;

const int MAXN=105;

char farm[MAXN][MAXN];
int m,n,cnt;

bool IsEdge(int x,int y)
{
    if(x>=0&&x<m&&y>=0&&y<n)
        return true;
    return false;
}

bool IsSame(int x,int y,char tree)
{
    if(farm[x][y]==tree)
        return true;
    return false;
}

void Dfs(int x,int y,char tree)
{
    int dir[]={0,1,0,-1,-1,0,1,0};
    for(int i=0;i<8;i+=2)
    {
        int dx=x+dir[i];
        int dy=y+dir[i+1];
        if(IsEdge(dx,dy)&&IsSame(dx,dy,tree))
        {
            farm[dx][dy]='-';
            Dfs(dx,dy,tree);
        }
    }
}

int main()
{
    while(cin>>m>>n,m&&n)
    {
        for(int i=0;i<m;i++)
        {
            cin>>farm[i];
        }
        cnt=0;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(farm[i][j]!='-')
                {
                    cnt++;
                    char tree=farm[i][j];
                    farm[i][j]='-';
                    Dfs(i,j,tree);
                }
            }
        }
        cout<<cnt<<endl;
    }
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/acm-jing/p/9550627.html