博客园 首页 私信博主 显示目录 隐藏目录 管理

UVA 572 Oil Deposits油田(DFS求连通块)

UVA 572     DFS(floodfill)  用DFS求连通块

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors. 

Given a diagram of Farmer John's field, determine how many ponds he has.

Input

* Line 1: Two space-separated integers: N and M 

* Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.

Output

* Line 1: The number of ponds in Farmer John's field.

Sample Input

10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

Sample Output

3

Hint

OUTPUT DETAILS: 

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

 

题解:输入m行n列的字符矩阵,统计字符“W”组成多少个八连块。如果两个字符“W”所在的格子相邻(横,竖或者对角线方向),就说它们属于同一个八连块,采用二重循环来找

        这就是连通块原理;每访问一次“W”,就给它写上标记的编号,方便检查。

 

AC代码:

#include<cstdio>
#include<cstring>
const int maxn=1000+5;
char tu[maxn][maxn];  //输入图的数组
int m,n,idx[maxn][maxn]; //标记数组

void dfs(int r,int c,int id)
{
    if(r<0||r>=m||c<0||c>=n)
        return;
    if(idx[r][c]>0||tu[r][c]!='W')
        return;
    idx[r][c]=id;
    for(int dr=-1; dr<=1; dr++)    
        for(int dc=-1; dc<=1; dc++)   // 寻找周围八块
            if(dr!=0||dc!=0)
                dfs(r+dr,c+dc,id);
}
int main()
{
    int i,j;
    while(scanf("%d%d",&m,&n)==2&&m&&n)
    {
        for(i =0; i<m; i++)
            scanf("%s",tu[i]);
        memset(idx,0,sizeof(idx));
        int q=0;
        for(i=0; i<m; i++)
            for(j=0; j<n; j++)
                if(idx[i][j]==0&&tu[i][j]=='W')
                    dfs(i,j,++q);
        printf("%d\n",q);
    }
    return 0;
}

 

posted @ 2015-07-22 08:26  hfcnal  阅读(1081)  评论(0编辑  收藏  举报