Benny has a spacious farm land to irrigate. The farm land is a rectangle, and is divided into a lot of samll squares. Water pipes are placed in these squares. Different square has a different type of pipe. There are 11 types of pipes, which is marked from A to K, as Figure 1 shows.
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 IHEthen 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.
There are several test cases! In each test case, the first line contains 2 integers M and N, then M lines follow. In each of these lines, there are N characters, in the range of 'A' to 'K', denoting the type of water pipe over the corresponding square. A negative M or N denotes the end of input, else you can assume 1 <= M, N <= 50.
<b< dd="">
For each test case, output in one line the least number of wellsprings needed.
<b< dd="">
Sample Input
2 2
DK
HF
3 3
ADC
FJK
IHE
-1 -1
Sample Output
2
3
题意概况:有11种水管给你每种水管的分布,问需要几个水源才能让所有的水管都有水?
解体思路:把每种水管都用3*3的01图表示,然后把你输入的每种水管的分布换成一个大的01图,然后找出有几组相连的1.
代码:
#include<stdio.h>
#include<string.h>
int a[200][200],book[200][200],m,n;
void dfs(int x,int y);
int main()
{
int i,j,k,l,t1,t2,t;
char s[60][60];
int b[11][3][3]={{{0,1,0},{1,1,0},{0,0,0}},
{{0,1,0},{0,1,1},{0,0,0}},
{{0,0,0},{1,1,0},{0,1,0}},
{{0,0,0},{0,1,1},{0,1,0}},
{{0,1,0},{0,1,0},{0,1,0}},
{{0,0,0},{1,1,1},{0,0,0}},
{{0,1,0},{1,1,1},{0,0,0}},
{{0,1,0},{1,1,0},{0,1,0}},
{{0,0,0},{1,1,1},{0,1,0}},
{{0,1,0},{0,1,1},{0,1,0}},
{{0,1,0},{1,1,1},{0,1,0}}};
while(scanf("%d%d",&m,&n)!=EOF)
{
if(m==-1&&n==-1)
break;
memset(a,0,sizeof(a));
for(i=1;i<=m;i++)
{
scanf("\n");
for(j=1;j<=n;j++)
{
scanf("%c",&s[i][j]);
t1=0;
for(k=i*3-2;k<=i*3;k++)
{
t2=0;
for(l=j*3-2;l<=j*3;l++)
{
a[k][l]=b[s[i][j]-'A'][t1][t2];
t2++;
}
t1++;
}
}
}
/*for(i=1;i<=m*3;i++)
{
for(j=1;j<=n*3;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}*/
memset(book,0,sizeof(book));
t=0;
for(i=1;i<=m*3;i++)
{
for(j=1;j<=n*3;j++)
{
if(a[i][j]==1)
{
if(book[i][j]==1)
continue;
else
{
dfs(i,j);
t++;
}
}
}
}
printf("%d\n",t);
getchar();
}
return 0;
}
void dfs(int x,int y)
{
int tx,ty,k;
int next[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
for(k=0;k<4;k++)
{
tx=x+next[k][0];
ty=y+next[k][1];
if(tx>m*3||tx<1||ty>n*3||ty<1)
continue ;
if(a[tx][ty]==1&&book[tx][ty]==0)
{
book[tx][ty]=1;
dfs(tx,ty);
}
}
}