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.
输入
输出
示例输入
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0
样本输出
0
1
2
2
不同的坐标表示形式,搜索时坐标代表含义不同,具体看代码
题意描述:
给n*m个数据,*表示没有油,@表示有油,如果@水平、垂直或对角线相邻,代表一个油田,求油田个数
解题思路:
利用深搜dfs,找到@开始遍历,深搜分八个方向,当走到的地方没有超届并且没有被标记过,就将这个地方标记成没有油田,以该点为起点继续遍历,直到搜索完,输出油田个数。
AC代码
# include <cstdio>
# include <iostream>
using namespace std;
char abc[120][120];
int m,n;
int i,j,k;
int ans;
int a[8]={-1,-1,0,1,1,1,0,-1};//等同 int vis[8][2]={{-1,0},{-1,1},{0,1},{1,1},{1,0],
int b[8]={0,1,1,1,0,-1,-1,-1}; {1,-1},{0,-1},{-1,-1}}
void dfs(int x,int y)
{
int k;
if(x<0 || y<0)
return; //这里的return返回很重要!!回溯
if(abc[x][y]=='@')
{
abc[x][y]='*';
for(k=0;k<8;k++)
dfs(x+a[k],y+b[k]); //等同int dx=x+vis[i][0]; //int dy=y+vis[i][1];
}
return;
}
int main()
{
int m,n;
while(scanf("%d%d",&m,&n)!=EOF&&(m||n))
{
int i,j;
int ans=0;
for(i=0;i<m;i++)
scanf("%s",abc[i]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(abc[i][j]=='@')
{
ans++;
dfs(i,j);
}
}
}
printf("%d\n",ans);
}
return 0;
}