Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4479 Accepted Submission(s): 1942
Figure 1
Benny has a map of his farm, which is an array of marks denoting the distribution of water pipes over the whole farm. For example, if he has a map
ADC
FJK
IHE
then the water pipes are distributed like
Figure 2
Several wellsprings are found in the center of some squares, so water can flow along the pipes from one square to another. If water flow crosses one square, the whole farm land in this square is irrigated and will have a good harvest in autumn.
Now Benny wants to know at least how many wellsprings should be found to have the whole farm land irrigated. Can you help him?
Note: In the above example, at least 3 wellsprings are needed, as those red points in Figure 2 show.
#include<stdio.h>
#include<string.h>
const int N = ;
int n,m;
char map[N][N];
int set[N*N];
int pipe[][] = {{,,,},{,,,},{,,,},{,,,},
{,,,},{,,,},{,,,},{,,,},
{,,,},{,,,},{,,,}
};//十一种水管,每四个数字描述一种管子,表示它的上右下左
//是否有管口; void init()
{
for(int i = ; i < n*m; i++)
set[i] = i;
} int find(int x)
{
if(set[x] != x)
set[x] = find(set[x]);
return set[x];
} int judge(char a, char b, int pos)
{
int x = a-'A';
int y = b-'A'; if(pos)
{
if(pipe[x][] == && pipe[y][] == )
return ;
else return ;
}
else
{
if(pipe[x][] == && pipe[y][] == )
return ;
else return ;
}
} void merge(int a,int b)
{
a = find(a);
b = find(b);
set[a] = b;
} int main()
{
int i,j;
while(~scanf("%d %d",&n,&m))
{
if(n == - && m == -)
break;
getchar();
init();
for(i = ; i < n; i++)
gets(map[i]); for(i = ; i < n; i++)
{
for(j = ; j < m; j++)
{
if(i != n-)
{
if(judge(map[i][j],map[i+][j],))//1表示两个字母所代表的管子位置关系是上下;
{
merge(i*m+j,(i+)*m+j);
}
}
if(j != m-)
{
if(judge(map[i][j],map[i][j+],))//0表示两个字母所代表的管子位置关系是左右;
{
merge(i*m+j,i*m+j+);
}
}
}
}
int count = ;
for(i = ; i < n*m; i++)
{
if(set[i] == i)
count++;
}
printf("%d\n",count); }
return ;
}