Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 46227 Accepted Submission(s): 26616
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.
问题连接
@代表油袋,*代表没油袋,如果两油袋相邻(横纵斜都算)则表示同一个油藏,给出分布求有多少个不同的油藏。
方法:DFS,即深度优先搜索。
根据题意,制作地图map[105][105]。表示各符号的位置。
用方向向量dirx[i],diry[i]控制方向。
visited[100][100]记录是否走过。
dfs(int,int);控制合理的移动
每全图遍历,就可以发现有多少个不同的油藏。
#include
using namespace std;
bool vis[100][100];//判断是否走过
int dix[8] = { -1, 0, 1, 1, 1, 0, -1, -1 };
int diy[8] = { 1, 1, 1, 0, -1, -1, -1, 0 };//方向向量
char Map[105][105];//地图
int m, n;//边界
void dfs(int, int);
int main()
{
while (cin >> m >> n)
{
if (m == 0)break;
memset(Map, '\0', sizeof(Map));//重置
memset(vis, 0, sizeof(vis));
int i, j, ans = 0;
for (i = 0; i < m; i++)//每排每排地输入
cin >> Map[i];
for (i = 0; i < m; i++)//全图检索
{
for (j = 0; j < n; j++)
{
if (Map[i][j] == '@'&&vis[i][j] == 0)//检索条件
{
ans++;
dfs(i, j);
}
}
}
cout << ans << endl;
}
return 0;
}
void dfs(int y, int x)//递归
{
if (y < 0 || y >= m || x < 0 || x >= n || Map[y][x] == '*' || vis[y][x] == 1) return;//不作处理
vis[y][x] = 1;//设置标记,表示已经走过
for (int i = 0; i < 8; i++)//延伸
{
dfs(y + diy[i], x + dix[i]);
}
}