uva572: 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.
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
0 1 2 2
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int maxn = 100 + 10; char dep[maxn][maxn]; int id[maxn][maxn]; //标记联通量id int row, col; void dfs(int r, int c, int num) { if(r >= row || r < 0 || c >= col || c < 0) return; //越界返回 if(dep[r][c] != '@' || id[r][c] != 0) return; //被访问过或者不是油田 id[r][c] = num; for(int i = -1; i <= 1; i++) for(int j = -1; j <= 1; j++) if(i != 0 || j != 0) dfs(r + i, c + j, num); //向周围8个方向深搜,注意if()中的条件,不遍历自己,否则就无限循环下去 } int main() { while(scanf("%d%d", &row, &col) == 2 && row && col) { for(int i = 0; i < row; i++) scanf("%s", dep[i]); int num = 0; memset(id, 0, sizeof(id)); for(int i = 0; i < row; i++) for(int j = 0; j < col; j ++) { if(id[i][j] == 0 && dep[i][j] == '@') dfs(i, j, ++num); } printf("%d\n", num); } return 0; }