Oil Deposits(经典DFS)

Oil Deposits     HDU - 1241

https://cn.vjudge.net/problem/HDU-1241
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
0
1
2
2

翻译

GeoSurvComp地质调查公司负责探测地下石油矿床。GeoSurvComp每次使用一个大的矩形区域,并创建一个网格,将该区域划分为多个正方形地块。然后对每个地块分别进行分析,利用传感设备确定地块是否含有石油。一块含有石油的地块叫做“口袋”。如果两个储集层相邻,那么它们是同一油藏的一部分。石油储量可能相当大,可能包含许多小块。你的工作是确定一个网格中包含多少不同的石油储量。
输入
输入文件包含一个或多个网格。每个网格以包含m和n的行开始,这是网格中的行数和列数,由单个空间分隔。如果m = 0,则表示输入结束;否则1 <= m <= 100和1 <= n <= 100。接下来是m行,每个行包含n个字符(不包括行尾字符)。每个角色对应一个情节,要么是“*”,代表没有油,要么是“@”,代表一个油袋。
输出
对于每个网格,输出不同的石油储量的数量。如果两个不同的储集层水平相邻、垂直相邻或对角相邻,那么它们就是同一个油藏的一部分。一个油藏的容量不会超过100个口袋。

思路

经典的DFS

代码
#include <bits/stdc++.h>
using namespace std;
char mp[105][105];
int n,m;
int dfs(int x,int y){
	if(mp[x][y]=='@'&&x<n&&x>=0&&y<m&&y>=0){//判断边界
		mp[x][y]='*';
		dfs(x+1,y),dfs(x-1,y),dfs(x,y+1),dfs(x,y-1);//向八个方向搜索
		dfs(x+1,y+1),dfs(x-1,y-1),dfs(x-1,y+1),dfs(x+1,y-1);
		return 1;
	}
	return 0;
}
int main() {
	while(~scanf("%d %d", &n, &m)&&(m||n)){
		memset(mp,0,sizeof(mp));
		for(int i=0;i<n;i++){
				scanf("%s", mp[i]);
		}
		int ans=0;
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				ans+=dfs(i,j);
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44410512/article/details/86766931