HD_1241Oil Deposits(DFS)

来源:互联网 发布:mysql修改连接密码 编辑:程序博客网 时间:2024/05/21 05:19
Problem Description
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid. 
 

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

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

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

Sample Output
0122
 
    题目大意很简单:统计字符'@'组成多少个八连块,既是有多少个互补联通的区域块在符合要求的情况下。如果两个字符'@'所在的格子相邻(横、竖、或者对角线方向),就说它们属于同一个八连块。思路就是深搜一下,然后对走过的标记一下,这里用的是vis数组。判断有几个区域可以看主函数里的那个双重循环。dfs里对同一块区域进行标记,直到标记完。
另外我是用两个for循环来设定八个方向的,既是(-1,-1),(-1,1),(-1,0),(0,-1),(0,1),(1,-1),(1,0),(1,1)。当然也可以用另外的方法,如用常量数组或者写8条dfs调用。具体看如下代码:

本题目链接

#include<cstdio>#include<cstring>using namespace std;const int maxn=100+5;char pic[maxn][maxn];int m,n,vis[maxn][maxn];void dfs(int r, int c, int id){if(r<0 ||r>=m || c<0 ||  c>=n )return ;//判断越界 if(vis[r][c]>0 || pic[r][c]!='@' )return ;//已经走过或者当点结点不是所要走的点既是不是@ vis[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(){while(scanf("%d%d",&m, &n)!=EOF && 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]==0 && pic[i][j]=='@')dfs(i,j,++cnt);}}printf("%d\n",cnt);}return 0; } 


0 0
原创粉丝点击