YT14-HDU-油井的种类

来源:互联网 发布:sql新增记录语句 编辑:程序博客网 时间:2024/05/08 00:27

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

0122


代码如下:

#include <iostream>using namespace std;char str[101][101];int m,n;const int dx[8]= {1,-1,0,0,1,1,-1,-1};const int dy[8]= {0,0,1,-1,1,-1,1,-1};void findpath(int p,int q){    int nx,ny,i;    for (i=0; i<8; i++)                   //向八个方向搜索。    {        nx=p+dx[i];        ny=q+dy[i];        if (str[nx][ny]=='@'&&p>=0&&q>=0&&p<m&&q<n)  //如果该位置是油井且在给定区域内        {            str[nx][ny]='.';               //如果该位置满足要求,将其表示为'.';即表示该位置已经被搜索过。            findpath(nx,ny);               //递归        }    }}int main(){    int i,j,k;    while (cin>>m>>n)    {        if (m==0||n==0)            break;        k=0;        for (i=0; i<m; i++)        {            for (j=0; j<n; j++)            {                cin>>str[i][j];                  //输入某区域内油井和非油井的字符图。            }        }        for (i=0; i<m; i++)        {            for (j=0; j<n; j++)            {                if(str[i][j]=='@')               //如果该位置是油井,搜索其八个方向是否有其他油井,直到找不到时,总油井数目+1                {                    findpath(i,j);                    k++;                                  }            }        }        cout<<k<<endl;                     //输出共有多少种油井    }    return 0;}

解题思路:

题目大意是某一区域内可能有多种油井和非油井,如果某一油井的周围(包括斜方向)也有油井,则它们属于同一油井,问这一区域内共有多少种油井?

还是递归,通过搜索某一方向一路搜到黑,然后从那一位置返回一步后搜索其他方向,这种方法是回溯法。

用’.’表示搜索成功的区域,防止二次被搜索。



1 0
原创粉丝点击