码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-22 09:11:56      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

 

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

标签:

原文地址:http://www.cnblogs.com/hfc-xx/p/4666223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!