Oil Deposits(油藏)(dfs经典模板题)POJ-1562

题目:Oil Deposits(油藏)


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 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
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 个口袋。
样本输入
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@
@
@@**@
0 0
样本输出
0
1
2
2

题意描述:输入为多实例,首先输入两个数字m,n,接着有n*m的字符矩形,*代表空地,@代表油田,如果两个油田相连(包括相邻和对角),那么他们就组成了一个大油田,要求输出这个矩形中共有几个油田,输入0 0表示结束。

解题思路:利用dfs思想,递归查找和记录。

错误分析:注意对单个小油田的处理,1*1的油田并不是大油田。

#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
int dir[8][2]={{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
char mp[105][105];
int n,m;

void dfs(int x,int y)
{
	mp[x][y]='*';//走过之后就标记或者改变,避免重复
	for(int i=0;i<8;i++)
	{//进行搜索
		int xx=dir[i][0]+x;
        int yy=dir[i][1]+y;
		if(mp[xx][yy]=='@'&&xx<n&&xx>=0&&yy<m&&yy>=0)//判断是否超出地图
		    dfs(xx,yy);//递归继续查找
	}
}
int main()
{
	while(scanf("%d %d",&n,&m)&&n&&m)
	{
		int sum=0;
		
		for(int i=0; i<n; i++){
			for(int j=0; j<m; j++)
			{
				cin>>mp[i][j];//存入地图
			}
		}
				
		for(int i=0; i<n; i++)
		{
			for(int j=0; j<m; j++)
			{
				if(mp[i][j]=='@')//找到一个小油田之后进行dfs搜索
				{
					dfs(i,j);
					sum++;
				}
			}	    
		}
		printf("%d\n",sum);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值