HDU 2412 Farm Irrigation

时间:2022-08-27 05:14:30

题目链接:

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2412

题目:

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.

HDU 2412 Farm Irrigation
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

HDU 2412 Farm Irrigation
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.

Input

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="">

Output

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

<b< dd="">Sample Output

2
3

题意描述:

输入矩阵的大小和字母表示的矩阵,表示不同型号的水管摆成的形状

解题思路:
题目还是很有意思的,实际就是找找有几个独立的连通区域。将对应字母型号的水管四个方向的状态存进数组,使用广搜遍历每个水管,判断在其方向上的水管的对应方向的状态即可。

代码实现:

 #include<stdio.h>
#include<string.h>
char map[][];
int m,n,book[][];
void bfs(int x,int y,int c);
struct n
{
int x,y;
};
int main()
{
int i,j,c;
while(scanf("%d%d",&m,&n), n!=- && m!= -)
{
for(i=;i<m;i++)
for(j=;j<n;j++)
scanf(" %c",&map[i][j]); memset(book,,sizeof(book));
for(c=,i=;i<m;i++){
for(j=;j<n;j++){
if(book[i][j]==)
bfs(i,j,++c);
}
}
printf("%d\n",c);
}
return ;
}
void bfs(int sx,int sy,int c)
{
struct n q[];
int i,tx,ty,head=,tail=,k;
int next[][]={,, ,, ,-, -,};
int list[]={,,,,,}; int alp[][]={,,,, ,,,, ,,,, ,,,, ,,,, ,,,,
,,,, ,,,, ,,,, ,,,, ,,,};//A到K的水管,每4个数表示一个水管,分别是右、下、左、上的状态
q[tail].x=sx;
q[tail].y=sy;
tail++;
book[sx][sy]=c;
while(head<tail)
{
for(k=;k<=;k++)
{
tx=q[head].x + next[k][];
ty=q[head].y + next[k][];
if(tx< || tx>=m || ty< || ty>=n)//设置边界
continue;
if(alp[ map[ q[head].x ][ q[head].y ]-'A' ][list[k]] && alp[ map[tx][ty]-'A' ][ list[k+] ] && !book[tx][ty])
{//对准位置
book[tx][ty]=c;
q[tail].x=tx;
q[tail].y=ty;
tail++;
}
}
head++;
}
}

易错分析:

1、注意遍历方向的时候要对准每个水管的对应方向的状态

2、边界设置要准确