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

来源:互联网 发布:淘宝卓富尼鞋 编辑:程序博客网 时间:2024/05/21 19:22

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
原创粉丝点击