三、搜索和二分 [Cloned] L - 搜索

原题:

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.

题意:

给出由两种符号表示的油田矩阵,如果@符号在八个方向相连则认为是一个油田,找出给的矩阵中有多少个油田。

题解:

深搜呗,定义一个visit数组来表示这个坐标是否来过,然后从头到尾搜索一遍油田矩阵,每次碰到每被搜索过的@就深搜一遍,然后油田数++,直到所有的位置都被搜索过一遍。

代码:AC

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1000;
typedef long long LL;
char s[MAX][MAX];
int n,m,vis[MAX][MAX],ans;
int fx[8] = {0,0,-1,1,-1,1,-1,1},fy[8] = {-1,1,0,0,-1,-1,1,1}; // 8 个方向 
void dfs(int x,int y){
    vis[x][y] = 1;
    for(int i = 0; i < 8; i++){
        int xx = x + fx[i],yy  = fy[i] + y;
        if(xx >= 0 && yy >= 0 && xx < n && yy < m && !vis[xx][yy] && s[xx][yy] == '@') // 判断是否出界, 是否已经搜索过, 是否为油田 
            dfs(xx,yy);
    }
}
int main()
{
    while(~scanf("%d %d",&n,&m),m){
        memset(vis,0,sizeof(vis));
        for(int i = 0; i < n; i++)
            scanf("%s",s[i]);
        ans = 0;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(!vis[i][j] && s[i][j] == '@')
                    ans++,dfs(i,j); // 第一次搜到 + 1 
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/npuyan/article/details/81416585
今日推荐