ZOJ 2412 Farm Irrigation(DFS)

就是用DFS找个数
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxm=55;
char map[maxm][maxm];
int DIR[22][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int dir[22][4] = {{0,0,1,1}, {1,0,0,1}, {0,1,1,0}, {1,1,0,0}, {0,1,0,1}, {1,0,1,0}, {1,0,1,1}, {0,1,1,1}, {1,1,1,0},{1,1,0,1}, {1,1,1,1}};
int vis[maxm][maxm];
int m,n;
void dfs(int x,int y,int t)
{
     vis[x][y]=1;
    for(int i=0; i<4; i++)
    {
        if(dir[t][i])
        {
            int xx=x+DIR[i][0];
            int yy=y+DIR[i][1];
            int k=map[xx][yy]-'A';
            if(xx>=0&&xx<m&&yy>=0&&yy<n&&!vis[xx][yy]&&dir[k][(i+2)%4])
            {
                dfs(xx,yy,k);
            }
        }
    }
}
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF&&(m+n)!=-2)
    {
        memset(vis,0,sizeof(vis));
        for(int i=0; i<m; i++)
        {
            scanf("%s",map[i]);
        }
        int cnt=0;
        for(int i=0; i<m; i++)
        {
            for(int j=0; j<n; j++)
            {
                if(!vis[i][j])
                {
                    dfs(i,j,map[i][j]-'A');
                    cnt++;
                }
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}

你可能感兴趣的:(ZOJ 2412 Farm Irrigation(DFS))