例题 6-12 油田 UVa 572 用dfs求连通块

572 - Oil Deposits

Time limit: 3.000 seconds

Oil Deposits


The GeoSurvComp geologic survey company is responsible fordetecting underground oil deposits. GeoSurvComp works with onelarge rectangular region of land at a time, and creates a grid thatdivides the land into numerous square plots. It then analyzes eachplot separately, using sensing equipment to determine whether ornot the plot contains oil.

A plot containing oil is called a pocket. If two pockets areadjacent, then they are part of the same oil deposit. Oil depositscan be quite large and may contain numerous pockets. Your job is todetermine how many different oil deposits are contained in agrid.

Input
The input file contains one or more grids. Each grid begins with aline containing m and n, the number of rows and columns in thegrid, separated by a single space. If m = 0 it signals the end ofthe input; otherwise and . Following this are m lines of ncharacters each (not counting the end-of-line characters). Eachcharacter corresponds to one plot, and is either `*', representingthe absence of oil, or `@', representing an oil pocket.

Output
For each grid, output the number of distinct oil deposits. Twodifferent pockets are part of the same oil deposit if they areadjacent horizontally, vertically, or diagonally. An oil depositwill not contain more than 100 pockets.

Sample Input
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0

Sample Output
0
1
2
2


分析:此题属于八连通块,每个点需要递归判断一下是否被判断过以及是否是@

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
const int maxn=105;
char pic[maxn][maxn];
int m,n;
bool vis[maxn][maxn];
void dfs(int r,int c)
{
    if(r<0||r>=m||c<0||c>=n)return; //边界处理
    if(vis[r][c]||pic[r][c]!='@')return; //已经访问过或者不是@
    vis[r][c]=1;
    for(int dr=-1;dr<=1;dr++){
        for(int dc=-1;dc<=1;dc++){
            if(dr!=0||dc!=0)dfs(r+dr,c+dc);
        }
    }
}
int main()
{
    while(scanf("%d%d",&m,&n)==2&&m&&n){
        for(int i=0;i<m;i++)
            scanf("%s",pic[i]);
        memset(vis,0,sizeof(vis));
        int cnt=0;
        for(int i=0;i<m;i++)
        for(int j=0;j<n;j++){
            if(!vis[i][j]&&pic[i][j]=='@'){
                dfs(i,j);
                 ++cnt;
            }
        }
       printf("%d\n",cnt);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值