专题二 第九道题

1.题目编号:1011

2.简单题意:有一个公司承担了检测石油资源的工作,工作时他们一次就探测一个矩形的区域,并将这个区域分成一个网格,分析每一个小网格决定是不是存在石油资源,含油的叫做pockets,但是如果相邻则为一个石油资源。给出网格的行列数m,n,其中每个网格中有#和@,@表示有石油,#表示没有石油,计算出有多少个石油资源

3.解题思路形成过程:刚看这个题的时候感觉它和red and black那道题差不多,就是运用深度搜索,不同的是他有八个方向而red and black就四个方向。需要注意的是两个相邻的含油pockets为一个石油资源

4.感悟:dfs和bfs真的很重要啊,如果会了基本思想这应该就算是简单题了,可是我还不怎么理解……没有建立起这个思维模式,怎么办怎么办大哭

5.AC的代码:

#include<iostream>
#include<string>
using namespace std;
int n,m;
char grid[101][101];
int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,1},{0,-1},{1,1},{1,0},{1,-1}};
void DFS(int x,int y)
{
    int i,a,b;
    grid[x][y]='0';
    for(i=0;i<8;i++)
    {
        a=x+dir[i][0];
        b=y+dir[i][1];
        if(a>=n||b>=m||a<0||b<0)
        continue;
        if(grid[a][b]!='*'&&grid[a][b]!='0')
        DFS(a,b);
    }
}
int main()
{
    int i,j;
    int count;
    while(cin>>n>>m,n)
    {
        cin.get();
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            cin>>grid[i][j];
            cin.get();
        }
        count=0;
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                if(grid[i][j]=='@')
                {
                    DFS(i,j);//从(i,j)位置进行DFS;
                    count++;
                }
            }
        }
        cout<<count<<endl;
    }
    return 0;
}

原题:

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. <br>


 


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.<br>


 


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.<br>


 


Sample Input


   
   
   
   
1 1<br>*<br>3 5<br>*@*@*<br>**@**<br>*@*@*<br>1 8<br>@@****@*<br>5 5 <br>****@<br>*@@*@<br>*@**@<br>@@@*@<br>@@**@<br>0 0 <br>


 


Sample Output


   
   
   
   
0<br>1<br>2<br>2<br>




你可能感兴趣的:(专题二 第九道题)