UVA 572(用DFS求连通图)

来源:互联网 发布:平价散粉推荐知乎 编辑:程序博客网 时间:2024/06/06 03:18

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
大家看原题吧,星花打的时候有问题。
Sample Output
0
1
2
2
题意:这道题是给你一块大油田,油田上有的地方有油,有的地方没油,油田某个地方有没有油是用的‘*’与‘@’来区分,‘@’代表有油,星花代表没油(星花打不出来),要求一共有多少块分开的油田,如果两块有油地方相邻,则算一块油田。
题解:先遍历所有区域,再用dfs来遍历油田附近的区域,如果有油则是同一块,用idx来表示是否这块油田已经被数过。

#include <iostream>#include <bits/stdc++.h>using namespace std;const int maxn = 100 + 5;char grid[maxn][maxn];bool idx[maxn][maxn];//用来存储这块小油田有没有被数过int m, n;void dfs(int r, int c, int id){    if (r < 0 || r >= m || c < 0 || c >= n) return;//出边界则返回,很重要    if (grid[r][c] != '@' || idx[r][c]) return;    idx[r][c] = true;//别忘了给idx赋值    for (int dr = -1; dr <= 1; dr++) {//8个方向遍历        for (int dc = -1; dc <= 1; dc++) {            if (dr != 0 || dc != 0) dfs (r + dr, c + dc, id);        }    }}int main(){    #ifndef ONLINE_JUDGE    freopen ("in.txt", "r", stdin);    #endif // ONLINE_JUDGE    while (scanf ("%d%d", &m, &n) != EOF && m && n) {        int cnt = 0;        memset (grid, '\0', sizeof(grid));        memset (idx, false, sizeof(idx));        for (int i = 0; i < m; i++) {            scanf ("%s", grid[i]);        }        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (grid[i][j] == '@' && idx[i][j] == false) {//用bool型变量时要注意用false、true,而不是0、1                    dfs (i, j, ++cnt);                }            }        }        printf ("%d\n", cnt);    }    return 0;}
0 0