用DFS求连通块

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.

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 and . 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
#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;
}

备注:对多维数组求联通块的过程也称之为“种子填充”。附上维基百科里面对于“种子填充”的介绍,动画很不错!https://en.wikipedia.org/wiki/Flood_fill

你可能感兴趣的:(用DFS求连通块)