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
问题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1241
问题简述:第一行输入两个数表示平面的行数跟列数,后面输入‘星号’与‘@’分别表示土地跟油田数,斜向相邻与四方向相邻的@表示同一片油田,输出油田的片数。
问题分析:先建一个int二维数组代表8个方向的方向单位向量,再建立一个与char数组相同的int二维数组用于判断深度搜索每个节点是否已经被搜索过。通过建立一个二维char数组平面表示油田,用深度搜索来搜索每一个油田(函数递归),在每一个函数结束的时候把@变成*,这样就能把所有八个方向连接到一起的@全部去除,再让油田总数+1即可。(要注意在每次输入结束后将判断数组跟油田数组初始化)
AC通过的C++语言程序如下:
#include<iostream>
using namespace std;
int fxxl[8][2] = { -1,1,0,1,1,1,-1,0,1,0,-1,-1,0,-1,1,-1 };
char p[105][105] = { '\0' };
int vst[105][105];
int k = 0;
int n, m;
void dfs(int x,int y)
{
vst[x][y] = 1;
for (int i = 0; i < 8; i++)
{
if (x + fxxl[i][0] >= 0 && y + fxxl[i][1] >= 0 && vst[x + fxxl[i][0]][y + fxxl[i][1]] != 1) {
if ((p[x + fxxl[i][0]][y + fxxl[i][1]]) == '@') {
dfs(x + fxxl[i][0], y + fxxl[i][1]);
}
}
}
p[x][y] = '*';
}
int main()
{
while (cin >> n) {
cin >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> p[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (p[i][j] == '@') {
dfs(i, j);
k++;
}
}
}
if (m != 0) { cout << k << endl; }
else { break; }
k = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
p[i][j] = '\0';
vst[i][j] = 0;
}
}
}
return 0;
}