HDU 1198 Farm Irrigation

来源:互联网 发布:不错吧源码 编辑:程序博客网 时间:2024/06/07 07:30

Farm Irrigation

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

ADCFJKIHE
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.


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.

Output

For each test case, output in one line the least number of wellsprings needed.

Sample Input
2 2DKHF3 3ADCFJKIHE-1 -1
Sample Output
23


 

题意:

每个字母代表上述的管道流向,求至少需要多少泉眼可全部灌溉农田。即为求管道相连的连通块数量。

制求此类方向问题方法:(总结)

 & 1 ==0 表示可以向左走
 & 2 ==0 表示可以向上走
 & 4 ==0 表示可以向右走
 & 8 ==0 表示可以向下走

 (依次对应于二进制的位数,做题时可以把难以描述的用数字来记录
  可以走的情况,然后用二进制进行方向走动。数字的确定可以利用
  二进制推出来。
  如:A 假设可以向 右 和 下 走
  则  4+8=12
 )


代码;

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;int n,m;int vis[55][55];int map[55][55];char c[55][55];void dfs(int x,int y){if(vis[x][y])return ;if(x<1||y<1||x>n||y>m)return ;vis[x][y]=1;if((map[x][y] & 1)  && (map[x][y-1] & 4)) dfs(x,y-1);if((map[x][y] & 2)  && (map[x-1][y] & 8)) dfs(x-1,y);if((map[x][y] & 4)  && (map[x][y+1] & 1)) dfs(x,y+1);if((map[x][y] & 8)  && (map[x+1][y] & 2)) dfs(x+1,y);}int main(){while(~scanf("%d%d",&n,&m)&&(n!=-1&&m!=-1)){memset(vis,0,sizeof(vis));for(int i=0;i<n;i++){scanf("%s",c[i]);for(int j=0;j<m;j++){if(c[i][j]=='A')map[i+1][j+1]=3;if(c[i][j]=='B')map[i+1][j+1]=6;if(c[i][j]=='C')map[i+1][j+1]=9;if(c[i][j]=='D')map[i+1][j+1]=12;if(c[i][j]=='E')map[i+1][j+1]=10;if(c[i][j]=='F')map[i+1][j+1]=5;if(c[i][j]=='G')map[i+1][j+1]=7;if(c[i][j]=='H')map[i+1][j+1]=11;if(c[i][j]=='I')map[i+1][j+1]=13;if(c[i][j]=='J')map[i+1][j+1]=14;if(c[i][j]=='K')map[i+1][j+1]=15;}}int sum=0;for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){if(!vis[i][j]){dfs(i,j);sum++;}}}printf("%d\n",sum);}return 0;}

输入的处理上可以用数组保存数字直接赋值,来简化操作!


原创粉丝点击