hdu1198 Farm Irrigation dfs

来源:互联网 发布:淘宝护肤品货源 编辑:程序博客网 时间:2024/05/17 23:22
Problem Description
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
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.
 

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思路:遍历地图 没被访问过的地方用dfs搜一遍并标记能达到的地方注意dfs的时候要判断当前位置与相邻位置是否互相连通 需要互相连通才能转移代码:
#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;int dir[4][2]= {0,-1,-1,0,0,1,1,0}; //左 上 右 下 顺时针 int ok[11][4]= {{1,1,0,0},{0,1,1,0},{1,0,0,1},{0,0,1,1},{0,1,0,1},{1,0,1,0},{1,1,1,0},{1,1,0,1},{1,0,1,1},{0,1,1,1},{1,1,1,1}}; //11块的4方向有无char map[55][55];int vis[55][55];int m,n;int t;void dfs(int x,int y){    int i,j,k;    if(x<1||y<1||x>m||y>n||vis[x][y])        return;    if(t!=5)     // 不是第一层递归  要判断与前小块是否互相连通    {        k=map[x][y]-'A';        if(ok[k][(t+2)%4]==0)            return;    }    vis[x][y]=1;    t=5;    k=map[x][y]-'A';    for(i=0; i<4; i++)    {        if(ok[k][i]==1)        {            t=i;            dfs(x+dir[i][0],y+dir[i][1]);        }    }    return;}int main(){    int i,j,ans;    while(~scanf("%d%d",&m,&n)&&m+n!=-2)    {        ans=0;        memset(vis,0,sizeof(vis));        for(i=1; i<=m; i++)            for(j=1; j<=n; j++)                cin>>map[i][j];        for(i=1; i<=m; i++)            for(j=1; j<=n; j++)            {                if(!vis[i][j])                {                    t=5;                    ans++;                    dfs(i,j);                }            }        cout<<ans<<endl;    }    return 0;}


0 0