Oil Deposits HDU - 1241(dfs入门题)

Text Reverse
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)

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 - 1241

问题简述:
有个人买了块地,想知道这块地里有多少块油田。

问题分析:
@代表着油田,它和它四周的@一起构成一块油田。

程序说明:
使用dfs进行连通,主程序判断是否为油田,若是,且未被编号,则导入dfs函数。dfs函数首先判断是否越界,该坐标是否为@(即是否是油田),是否已被连通,符合条件进行下一步。将该坐标进行编号,然后搜索它的四周是否也有@,若有则将其编号(编号与该油田的编号相同)。

#include <iostream>
#include<stdio.h>
using namespace std;
const int maxn=100+5;//这样定义方便在别的题目中修改范围,因为刚好的数组容易出错,故定义的比题目范围稍大一些
int idx[maxn][maxn];//此处使用全局变量定义dfs的范围
int m, n;
char a[maxn][maxn];//油田
void dfs(int r, int c, int id)
{
	if (r < 0 || r >= m || c < 0 || c >= n || idx[r][c] != 0 || a[r][c] != '@') return;//首先判断是否越界,该坐标是否为@(即是否是油田),是否已被连通,符合条件进行下一步。
	idx[r][c] = id;//将该坐标进行编号
	for(int dr=-1;dr<=1;dr++)//搜索它的四周是否也有@,若有则将其编号(编号与该油田的编号相同)
		for (int dc = -1; dc <= 1; dc++)
		{
			if (dr != 0 || dc != 0)
				dfs(dr + r, dc + c, id);
		}
}
int main() 
{
	while (cin >> m >> n)
	{
		if (m == 0 || n == 0)
			break;
		for (int i = 0; i < m; i++)
		{
			cin >> a[i];
		}
		memset(idx, 0, sizeof(idx));//初始化dx数组内的数值为0
		int id = 0;
		for(int i=0;i<m;i++)
			for (int j = 0; j < n; j++)
			{
				if (a[i][j] == '@' && idx[i][j] == 0)
				{
					dfs(i, j, ++id);//这里写id++会re
				}
			}
		cout << id << endl;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_44012551/article/details/86603862