Oil Deposits

OIl Deposite

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

题目大意:多组输入,每次输入整数m、n,若m、n为0 0输入结束;否则输入一个m*n的矩阵,表示m*n的土地中的油气储存情况。规定矩阵中‘*’为没有油气的土地,而‘@’为有油气,当两个有油气的土地相邻时,(即以一个有油气的土地为例,它周围八个格子内的有油气的土地,则称它俩相邻)。相邻的有油气的土地称为一块油田。问输入的矩阵内有几块油田。

思路:深搜,递归回溯每一个格子,每到一块有油气的格子,就替换掉它的油气信息。代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <string.h>
using namespace std;
const int max_n=103;
char mp[max_n][max_n];
int m,n,sum;
bool judge(int x,int y)
{
    return x>=0&&x<m&&y>=0&&y<n;
}
void dfs(int x,int y)
{
    mp[x][y]='*';//替换当前位置
    for(int dx=-1;dx<=1;dx++)//遍历周围的八个格子
    {
        for(int dy=-1;dy<=1;dy++)
        {
            int nx=x+dx,ny=y+dy;
            if(judge(nx,ny)&&mp[nx][ny]=='@')dfs(nx,ny);//当有油气时,递归
        }
    }
    return;
}
int main()
{
    while(scanf("%d %d",&m,&n)==2)
    {
        if(m==0&&n==0)break;
        sum=0;
        for(int i=0;i<m;i++)
        {
            cin>>mp[i];
        }
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(mp[i][j]=='@')//当有油气时
                {
                    dfs(i,j);//替换它以及他周围的同一油田的格子
                    sum++;//计数器加1
                 } 
            }
        }
        printf("%d\n",sum);
        memset(mp,0,sizeof(mp));
    }
    return 0;
}

 
posted @ 2019-07-26 08:55  whocarethat  阅读(90)  评论(0编辑  收藏  举报