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.(问题描述;GeoSurvComp地质勘测公司负责探测地下石油储藏。GeoSurvComp每次处理一大片矩形土地,并创建一个网格,将土地分成许多正方形地块。然后,它使用传感设备分别分析每个地块,以确定该地块是否含有石油。含有石油的地块称为口袋。如果两个口袋相邻,那么它们是同一个油藏的一部分。石油储量可能相当大,可能包含许多口袋。你的工作是确定一个网格中包含多少不同的石油储量。)
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.(投入;输入文件包含一个或多个网格。每个网格以一条包含m和n的线开始,m和n是网格中的行数和列数,由一个空格分隔。如果m = 0,则表示输入结束;否则1 <= m <= 100和1 <= n <= 100。接下来是m行n个字符(不包括行尾字符)。每个字符对应一个图,或者是表示没有油的“*”,或者是表示油囊的“@”。)
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.(输出;对于每个网格,输出不同油藏的数量。如果两个不同的油囊在水平方向、垂直方向或对角线方向相邻,则它们是同一油藏的一部分。一个油藏不会包含超过100个口袋。)
#include "cstdio"
using namespace std;
const int maxnum = 111;
char map[maxnum][maxnum];
int n,m;
int dx[] = {0,0,1,1,1,-1,-1,-1};
int dy[] = {1,-1,1,-1,0,1,-1,0};
bool check(int x, int y){ //判断是否被访问过。
if(x >= 0 && x < n && y >= 0 && y < m && map[x][y] == '@') //判断x,y是否出界,是油田的话是 @ ,
return 1;
return 0;
}
void dfs(int x, int y) {
if (!check(x, y)) // 寻找不是油田的坐标点。
return;
map[x][y] = '*'; // 遍历过的是 *。
for (int i = 0; i < 8; i++) // i 为八个方向的判断。
dfs(x + dx[i], y + dy[i]); // 遍历整个数组图。找到哪里是油田,哪里不是油田,把整个图都串起来。
}
int main(){
while(scanf("%d %d", &n, &m),m){ // 输入横纵坐标。
if ( n == 0 && m == 0)
break; // 去掉原点。
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%s", map [i][j]); // 输入地图。
int num = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++){
if(map[i][j] == '@'){ // 遍历全图并判断坐标点是否是油田。
num++; // 油田块数加一。
dfs(i,j); // 遍历全图。
}
}
printf("%d\n", num);
}
return 0;
}