Oil Deposits
| Oil Deposits |
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; otherwiseOutput
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
方法 :
简单深度优先遍历。
代码 :
#include #define N 102 char grid[N][N]; void dfs(int x, int y) { grid[x][y] = '*'; if(grid[x][y+1] == '@') dfs(x, y+1); if(grid[x+1][y+1] == '@') dfs(x+1, y+1); if(grid[x+1][y] == '@') dfs(x+1, y); if(grid[x+1][y-1] == '@') dfs(x+1, y-1); if(grid[x][y-1] == '@') dfs(x, y-1); if(grid[x-1][y-1] == '@') dfs(x-1, y-1); if(grid[x-1][y] == '@') dfs(x-1, y); if(grid[x-1][y+1] == '@') dfs(x-1, y+1); } int num_of_oil(int m, int n) { int i, j, s; s = 0; for(i = 1; i<= m; i++){ for(j = 1; j <= n; j++){ if(grid[i][j] == '@'){ s++; dfs(i, j); } } } return s; } int main() { int m, n, i, j; while(scanf("%d %d", &m, &n) != EOF && m != 0){ for(i = 1; i <= m; i++){ scanf("%s", grid[i]+1); grid[i][0] = '*'; grid[i][n+1] = '*'; } for(j = 0; j <= n+1; j++){ grid[0][j] = '*'; grid[m+1][j] = '*'; } printf("%d\n", num_of_oil(m, n)); } return 0; }

本文介绍了一种使用简单深度优先搜索算法来探测并计算矩形区域内地下油藏数量的方法。通过将区域划分为多个正方形地块,并对每个地块进行单独分析以确定是否含有油藏。两个相邻的油藏被视为同一个油藏的一部分。
526

被折叠的 条评论
为什么被折叠?



