Oil Deposits题目传送

Oil Deposits

Oil Deposits
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 52914 Accepted Submission(s): 30411

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
0
1
2
2
这道题DFS和BFS都可以写的,下面的用法是DFS
具体解释看代码,里面有注释

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>

using namespace std;
bool vis[120][120];//标记
int M,N;
int ans;//结果
int dir[8][2]={1,0,-1,0,0,1,0,-1,1,1,-1,-1,1,-1,-1,1};//方向,这题是八个方向
char s[120][120];//存图
void DFS(int x,int y)
{
	vis[x][y]=1;
	if(x<0||x>=M||y<0||y>=N)//如果走出了区域范围,则结束递归
	return ;
	for(int i=0;i<8;i++)
	{
		int X,Y;
		X=x+dir[i][0];
		Y=y+dir[i][1];
		if(!vis[X][Y]&&s[X][Y]=='@')//如果之前没有走过,并且此方向可以走
		{
			DFS(X,Y);
		}
	}
	return ;	
}
int main()
{
	while((scanf("%d%d",&M,&N),M)||N)
	{
		getchar();
		int i,j;
		for(i=0;i<M;i++)
		{
			scanf("%s",s[i]);
		}
		memset(vis,0,sizeof(vis));
		ans=0;
		for(i=0;i<M;i++)
		{
			for(j=0;j<N;j++)
			{
				if(!vis[i][j]&&s[i][j]=='@')//如果之前没有做标记,说明这是新的一块油田,因为油田是一片区域,看有多少块不连通的油田
				{
					DFS(i,j);//把这一片区域做上标记,能走到的属于同一块油田
					ans++;
				}
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}

多谢捧场,希望能帮助你,加油!程序猿