主要难点在构图,其实也不难,然后就是运用并查集,
把能够连通的成为一个集合,最后看有多少个集合就是所求的解。
#include<stdio.h>
int n,m;
const int maxn = 60 ;
struct node
{
int up;
int down;
int left;
int right;
}list[maxn][maxn];
int father[4000];
void success(int i,int j,char s)
{
if(s=='A')
{
list[i][j].up = 1;
list[i][j].down = 0;
list[i][j].left = 1;
list[i][j].right = 0;
}
else if(s=='B')
{
list[i][j].up = 1;
list[i][j].down = 0;
list[i][j].left = 0;
list[i][j].right = 1;
}
else if(s=='C')
{
list[i][j].up = 0;
list[i][j].down = 1;
list[i][j].left = 1;
list[i][j].right = 0;
}
else if(s=='D')
{
list[i][j].up = 0;
list[i][j].down = 1;
list[i][j].left = 0;
list[i][j].right = 1;
}
else if(s=='E')
{
list[i][j].up = list[i][j].down = 1;
list[i][j].left = list[i][j].right = 0;
}
else if(s=='F')
{
list[i][j].up =list[i][j].down = 0;
list[i][j].left = list[i][j].right = 1;
}
else if(s=='G')
{
list[i][j].up = list[i][j].left = list[i][j].right = 1;
list[i][j].down = 0;
}
else if(s=='H')
{
list[i][j].up = list[i][j].down = list[i][j].left = 1;
list[i][j].right = 0;
}
else if(s=='I')
{
list[i][j].up = 0;
list[i][j].down = list[i][j].left = list[i][j].right = 1;
}
else if(s=='J')
{
list[i][j].left = 0;
list[i][j].up = list[i][j].down = list[i][j].right = 1;
}
else if(s=='K')
{
list[i][j].up = list[i][j].down = list[i][j].left = list[i][j].right = 1;
}
}
int finds(int x)
{
if(x==father[x]) return x;
else return finds(father[x]);
}
void bing(int x,int y)
{
father[finds(x)] = father[finds(y)];
}
void fun(int x,int y)
{
if(list[x][y].up && list[x-1][y].down )
bing(x*60+y,(x-1)*60+y);
if(list[x][y].down && list[x+1][y].up )
bing(x*60+y, (x+1)*60+y);
if(list[x][y].left && list[x][y-1].right)
bing(x*60+y,x*60+y-1);
if(list[x][y].right && list[x][y+1].left )
bing(x*60+y,x*60+y+1);
}
int main()
{
int i,j;
char s;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==-1 && m==-1) break;
for(i=0;i<maxn;i++)
for(j=0;j<maxn;j++)
{
father[i*60+j] = i*60+j;
list[i][j].up = list[i][j].down = list[i][j].left = list[i][j].right = 0;
}
getchar();
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%c",&s);
success(i,j,s);
}
getchar();
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
fun(i,j);
}
int ans = 0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(father[i*60+j] == i*60+j) ans ++;
printf("%d\n",ans);
}
return 0;
}