题目连接 : http://acm.hdu.edu.cn/showproblem.php?pid=1198
#include<stdio.h>
#include<string>
#include<cstring>
#include<queue>
#include<algorithm>
#include<functional>
#include<vector>
#include<iomanip>
#include<math.h>
#include<iostream>
#include<sstream>
#include<stack>
#include<set>
#include<bitset>
#include<map>
using namespace std;
const int MAX = 550;
//左上右下
const int type[11][4]= {{1,1,0,0},{0,1,1,0},
{1,0,0,1},{0,0,1,1},
{0,1,0,1},{1,0,1,0},
{1,1,1,0},{1,1,0,1},
{1,0,1,1},{0,1,1,1},
{1,1,1,1}};
const bool VERTICAL = true;
int pre[MAX*MAX+1],cnt,m,n; //转化为一维标号
char farm[MAX][MAX];
void init(int n)
{
int i;
for(i=1; i<=n; ++i)
{
pre[i] = i;
}
cnt = n;
}
int root(int x)
{
if(x!=pre[x])
{
pre[x] = root(pre[x]);
}
return pre[x];
}
void merge(int ax,int ay,int bx,int by,bool dir)
{
if(bx>n || by>m)return;
bool mark = false;
int ta,tb;
ta = farm[ax][ay]-'A';
tb = farm[bx][by]-'A';
if(dir)
{
if(type[ta][3] && type[tb][1])mark = true;
}
else
{
if(type[ta][2] && type[tb][0])mark = true;
}
if(mark)
{
int fx = root((ax-1)*m+ay);
int fy = root((bx-1)*m+by);
if(fx!=fy)
{
pre[fy] = fx;
--cnt;
}
}
}
int main()
{
int i,j;
while(scanf("%d %d",&n,&m)!=EOF)
{
if(n==-1 && m==-1)break;
init(n*m);
for(i=1; i<=n; ++i)
{
scanf("%s",farm[i]+1);
}
for(i=1; i<=n; ++i)
{
for(j=1; j<=m; ++j)
{
merge(i,j,i+1,j,VERTICAL);
merge(i,j,i,j+1,!VERTICAL);
}
}
printf("%d\n",cnt);
}
return 0;
}