算法 acm dfs 油田问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/li_jeremy/article/details/82746308

今天开始学习算法,DFS一个关于油田的问题,具体看问题描述和代码。

问题描述
GeoSurvComp地质调查公司负责探测地下石油储藏。 GeoSurvComp现在在一块矩形区域探测石油,并把这个大区域分成了很多小块。他们通过专业设备,来分析每个小块中是否蕴藏石油。如果这些蕴藏石油的小方格相邻,那么他们被认为是同一油藏的一部分。在这块矩形区域,可能有很多油藏。你的任务是确定有多少不同的油藏。
Input
输入可能有多个矩形区域(即可能有多组测试)。每个矩形区域的起始行包含m和n,表示行和列的数量,1<=n,m<=100,如果m =0表示输入的结束,接下来是n行,每行m个字符。每个字符对应一个小方格,并且要么是’*’,代表没有油,要么是’@’,表示有油。
Output
对于每一个矩形区域,输出油藏的数量。两个小方格是相邻的,当且仅当他们水平或者垂直或者对角线相邻(即8个方向)。
Sample Input
1 1
*
3 5
@@*
@
@@*
1 8
@@*@
5 5
*@ @@@ @@
@@@@ @@*@
0 0
Sample Output
0
1
2
2

#include <iostream>
#include<string.h>
using namespace std;
const int N =105;       //N值为常量 
char s[N][N];           //存储输入的符号 
int d[8][2]={{1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};  //用于验证8个方向 
bool map[N][N];          //标记 看是否访问过 
int n,m;
void dfs(int x,int y){   //深搜核心 
    int i,tx,ty;
    map[x][y]=false;     //访问过的标记未false 
    i=0;
    while(i<8){         
        tx=x+d[i][0];   //8个方向验证有没有连着的 
        ty=y+d[i][1];
        if(tx>=0&&ty>=0&&ty<n&&ty<m&&s[tx][ty]=='@'&&map[tx][ty]){
            dfs(tx,ty);    //如果有递归调用Dfs 
        }
        i++;
    }
    return;
}
int main(){
    int i,j,ans;
    while(cin>>n>>m){
        i=0;
        while(i<n)
            cin>>s[i++];
        memset(map,true,sizeof(map));   //memset将map全部置为true 
        ans=0;                   //油田数量 
        i=0;
        while(j<m){
            if(s[i][j]=='@'&&map[i][j]){    //如果是 进行dfs 
                dfs(i,j);
                ans++;
            }
            j++;
        }
        i++;
    }
    cout<<ans<<endl;
    return 0;
}

如有不对欢迎批评指正。

猜你喜欢

转载自blog.csdn.net/li_jeremy/article/details/82746308