杭电 1241 Oil Deposits (DFS求连通图)

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.

Sample Input

1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5 
****@
*@@*@
*@**@
@@@*@
@@**@
0 0 

Sample Output

0
1
2
2

这就是一个简单的求连通图问题的题目,第一眼就断定是一个dfs,我们知道求连通图问题可以使用并查集,dfs…没想到我搜题解的时候竟然搜到了bfs的代码,确实很牛逼,不过对于类似这种题目建议使用dfs去求解。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <string.h>
using namespace std;
int d[8][2] = {
   0, -1, 0, 1, 1, 0, -1, 0, 1, -1, -1, 1, 1, 1, -1, -1};
int a[1000][1000], vis[1000][1000];
char c[1000][1000], ans;
int n, m;
void dfs(int x, int y)
{
   
    for (int i = 0; i < 8; ++i)
    {
   
        int nx = x + d[i][0];
        int ny = y + d[i][1];
        if (c[nx][ny] == '@' && nx >= 1 && nx <= n && ny >= 1 && ny <= m && !vis[nx][ny])
        {
   
            vis[nx][ny] = 1;
            dfs(nx, ny);
        }
    }
}
int main()
{
   
    int sum;
    while (~scanf("%d%d", &n, &m))
    {
   
        if (n == 0)
            return 0;
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
                scanf(" %c", &c[i][j]);
        memset(vis, 0, sizeof(vis));
        sum = 0;
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
            {
   
                if (c[i][j] == '*' || vis[i][j])
                    continue;
                vis[i][j] = 1;
                dfs(i, j); //每dfs一遍就是一个连通图
                sum++;
            }
        printf("%d\n", sum);
    }
    return 0;
}
愿你生命中有够多的云翳,来造成一个美丽的黄昏
全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
offer小狗:就这样上秋招??
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务