SHUOJ 数油田

描述

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

想法

这道题用的算法是深度优先搜索(DFS),当然广度优先(BFS)也可以,寻找有多少油田就类似于找一个图中有多少个连通分支。由于题干中说了对角线也是邻接关系,所以对于每一个油井来说存在8个搜索的方向。若方向上存在油井表示此方向路径连通,属于同一个连通分支也就是一个油田。

代码

#include <iostream>
using namespace std;

char s[101][101];//照应题干m和n从1开始,第0行和第0列空出
int m,n;
int i,j;

void dfs(int x,int y)
{
    if(x<1 || x>m || y<1 || y>n)  //处理出界情况
        return;
    if(s[x][y] != '@')  //不是油田就跳过
        return;
    s[x][y]='*';  //已经扫描过油井的置为“无油”,避免重复搜索
    for(int i=-1;i<=1;i++)
        for(int j=-1;j<=1;j++)  //从左上角开始顺时针扫描8个方向
            dfs(x+i,y+j);
}
int main()
{
    while(cin>>m>>n)
    {
        int count=0;
        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++)
            cin>>s[i][j];

        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++)
            {
                if(s[i][j]=='@')
                {
                    dfs(i,j);//深搜
                    count++;//DFS了多少次,就有多少个连通的油田
                }
            }
        if(m)//题干中以m==0为输入结束,不需要输出
            cout<<count<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/waveviewer/article/details/81192155