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 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在一片大的长方形土地上同时工作,用栅栏将土地分成众多的正方形土地。分别对每一块进行分析,用感应设备去确定土地是否包含油矿。
一个蕴藏石油的土地叫做“pocket".如果了两个”pocket"毗邻,则把他们认为是一块相同的油矿。油矿可能很大也可以包含众多的"pocket",你的工作就是确定:在一个栅栏中,有多少不同的油矿被包含。
输入
输入的信息包含一个或更多的栅栏。每一个栅栏开始于包含m和n的一行(代表一个栅栏的行和列),用空格隔开。如果m=0标志着输入停止(1<=m<=100,1<=n<=100)。在这之下是包含n个符号的m行(没有数最后一行的数字)。每一个符号对应一小块土地,*表示没有油,@表示一个油矿。
输出
对于每一个栅栏区域,输出明显的油矿数目。如果他们是横向纵向或者对角线毗邻,两个不同的"pocket"被认为是同一块油矿。一个油矿最多有100个"pocket"
深搜:每次都是沿着路径到不能再前进时才退回到最近的岔路口。
基本思路:将经过的顶点设置为已访问,在下次递归碰到这个顶点时就不再去处理,直到整个图的顶点都被标记为已访问
#include<stdio.h>
#include<iostream>
using namespace std;
int m,n,cnt=0;
char a[101][101];
//深度搜索
void dfs(int row,int col)
{
//包含此油田和它周围八个点的遍历
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
{
if(i==0&&j==0) continue;//如果是它本身
if(row+i<0||row+i>=m||col+j<0||col+j>=n) continue;//如果越界
if(a[row+i][col+j]=='*') continue;//如果不是油田
a[row+i][col+j]='*';//如果是油田,则把油田标记为'*',表示遍历过了
dfs(row+i,col+j);//对此油田再次深搜
}
}
int main()
{
//输入数组
cin>>m>>n;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
//判断是否是油田,若是则深搜
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(a[i][j]=='@')
{
a[i][j]='*';
dfs(i,j);
cnt++;//深搜结束代表一大块油田遍历结束,此一大块油田计入总数
}
}
cout<<cnt;
return 0;
}