思路:找到一个'@'即一个油田,往米字8个方向继续探测,直到再也找不到相邻油田,才使计数变量cnt+1。遍历地图上所有单元,直到再没有'@'。(找到一个油田就要把'@'改为'*'才不会重复搜索)。
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
#include<iostream>
#include<cstring>
#include<cstdio>
char a[105][105];
int row,col;
int dir[8][2]=
{
{1,0}, //右
{1,1}, //右上
{1,-1}, //右下
{0,-1}, //下
{0,1}, //上
{-1,0}, //左
{-1,1}, //左上
{-1,-1} //左下
};
using namespace std;
void dfs(int i,int j)
{
a[i][j]='*'; //找到一个相邻油田就把它改为'*'避免重复搜索,相当于置visit=1
for (int k=0;k<8;k++)
{
int x=i+dir[k][0];
int y=j+dir[k][1];
if (x>=1&&x<=row&&y>=1&&y<=col&&a[x][y]=='@')
dfs(x,y);
//探测周围八个方向,若都没有油田@,返回上层递归
//这里找不到就退出当前递归,不用再像其他dfs题目需要将*置为@,找不到就说明这块油田就只有这么大,不是非要找出一条通路的那种情况。
}
return ;
}
int main()
{
while ((cin>>row>>col)&&(row!=0||col!=0))
{
int cnt=0;
getchar();
for (int i=1;i<=row;i++)
for (int j=1;j<=col;j++)
cin>>a[i][j];
for (int i=1;i<=row;i++)
for (int j=1;j<=col;j++)
if (a[i][j]=='@')
{
dfs(i,j);
cnt++; //执行这一步说明与当前油田属于同一油田的单元已经全部搜寻完毕,cnt+1
//而且执行完当前的dfs之后,找到的成块油田已经全部用*取代,所以下一层for循环不会重复探测。
}
cout << cnt << endl;
}
return 0;
}