0
点赞
收藏
分享

微信扫一扫

HDU-1241 Oil Deposits DFS深搜题解


● 本题解会有详细的分析,适合初学者阅读

原题

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

题目翻译

Problem Description

GSC(这人探测石油的)要处理一个大的矩形土地,并创建一个网格,将土地划分为多个方形区域。然后分别分析每个区域,利用传感设备确定地块是否含油。含有石油的地块被称为“Pocket”。如果两个Pocket相邻,则它们是同一个Pocket的一部分。石油储量可能相当大,并且可能包含许多小Pocket。你的工作是确定在这片举行区域中包含多少不同的石油矿藏。

Input

多组输入。每个矩形土地的参数:从一行开始,其中包含m和n,即网格中的行数和列数,用单个空格分隔。如果m=0,则表示输入结束;否则1<=m<=100和1<=n<=100。接下来是m行,每行n个字符(不包括行尾字符)。每个字符对应一个状态,要么是’’*’,表示无油,要么是`@’,表示有油(即为Pocket)。

Output

对于每个矩形土地,输出不同石油矿藏的数量。如果两个不同的Pocket水平、垂直或对角相邻,则它们是同一油藏的一部分。一个Pocket的容量不会超过100个。

题目分析

题目描述的有点绕,但是不难理解,显然是道搜索题,而且可以说是入门级的搜索水题,连回溯都免了

我们的目的是要找出有多少不同的Pocket,我们只需要线性扫描整个图,每碰到一个Pocket点就以该点为起点测试周围Pocket点的联通性,如果联通,那么将能联通的部分全部删除,标记为普通区域,同时计数器++,整张图线性扫描完后,计数器即是答案。这里给出一个简单的示意动画。

HDU-1241 Oil Deposits DFS深搜题解_#define

碰到第一个油桶,就递归的向全方向搜,知道搜不到连接的区域为止,继续线性扫描整个土地。剩下的动画自行脑补,真的…懒得做了…

AC Code

#include <bits/stdc++.h>
#define
#define
using namespace std;
const int a[] = {1,1,0,-1,-1,-1,0,1};
const int b[] = {0,1,1,1,0,-1,-1,-1};
char g[105][105];
int n, m, ans;

void dfs(int x, int y)
{
g[x][y] = '*';
for(int i = 0; i < 8; i++){
if (g[xa][yb] == '@' && xa < n && xa >= 0 && yb < m && yb >= 0) dfs(xa, yb);
}
}
int main(){
while(cin >> n >> m){
getchar(); //将无效的空行吞掉
ans = 0;
if(!n && !m) break;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++) cin >> g[i][j];
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(g[i][j] == '@'){
dfs(i, j);
ans++;
}
}
}
cout << ans << endl;
}
return 0;
}


举报

相关推荐

0 条评论