hdu1241——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 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求连通块的问题,第二次写了,这次自己写了出来,虽然还是写了很久

代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int n,m;
const int MAXN=105;
char mp[MAXN][MAXN];
int vis[MAXN][MAXN];
int cnt;
int dir[8][2]={
  {-1,-1},{
  0,-1},{
  1,-1},{-1,0},{
  1,0},{-1,1},{
  0,1},{
  1,1}};
bool check(int i,int j){
    if(i<0 || i>=n || j<0 || j>=m || vis[i][j] || mp[i][j]=='*'){
        return false;
    }
    return true;
}
void dfs(int i,int j,int idx){
    vis[i][j]=idx;
    int ti;
    int tj;
    for(int k=0;k<8;k++){
        ti=i+dir[k][0];
        tj=j+dir[k][1];
        if(check(ti,tj)){
            dfs(ti,tj,idx);
        }
    }
}
void init(){
    memset(mp,'\0',sizeof(mp));
    memset(vis,0,sizeof(vis));
    cnt=0;
}
int main(void){
    //freopen("data.txt","r",stdin);
    while(~scanf("%d%d",&n,&m) && n && m){
        init();
        for(int i=0;i<n;i++){
            scanf("%s",mp[i]);
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(mp[i][j]=='@' && !vis[i][j]){
                    dfs(i,j,++cnt);
                }
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
Yki_:你要算时间成本呀,研究生两三年,博士三四年,加起来就五六年了,如果你本科去腾讯干五年,多领五年的年薪,加上公司内涨薪,可能到时候十五年总薪资也跟博士差不多
点赞 评论 收藏
分享
05-20 21:57
已编辑
门头沟学院 Java
喜欢吃卤蛋的悲伤蛙在...:建信融通没消息吧,我2说有实习挂简历不理了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务