Oil Deposits

来源:互联网 发布:java培训mobiletrain 编辑:程序博客网 时间:2024/04/29 23:02
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>
 

Source
Mid-Central USA 1997
简单题意:
  一个m*n的地图,其中的格子要么是*,要么是@,对于@,横竖斜着的成为一个块,现在要求编写一个程序求出总共有多少@块。
解题思路形成过程:
  这是最最经典的深搜题目。老师在课上也讲过,所以思路自然而然的就有了。dfs函数写出来,一切就都结束了。
感想:
  课上的例题也是最经典的一部分。对于经典,本就是不可重现的模板。
AC代码:
#include <iostream>
#include <cstring>   
using namespace std;
bool visit[110][110];
char maze[110][110]; 
int dir[8][2]={{-1,0},{1,0},{0,1},{0,-1},{-1,-1},{-1,1},{1,-1},{1,1}}; 
int sum,m,n,sx,sy;
bool isbound(int a,int b){  
    if(a<1 || a>m || b<1 || b>n)return true;
    return false;
}
void dfs(int sx,int sy){
    
    
    for(int i=0;i<8;i++)
    {
        if(maze[sx+dir[i][0]][sy+dir[i][1]]=='*')continue;
        if(isbound(sx+dir[i][0],sy+dir[i][1]))continue;
        if(visit[sx+dir[i][0]][sy+dir[i][1]])continue;
          visit[sx+dir[i][0]][sy+dir[i][1]]=1; 
          dfs(sx+dir[i][0],sy+dir[i][1]);
    }
}
int main()
{
    while(cin>>m>>n)
    {
        if(m==0)break;
        memset(visit,0,sizeof(visit));
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                cin>>maze[i][j];
            }
        }
        sum=0;
        for(int i=1;i<=m;i++){    
            for(int j=1;j<=n;j++){
                if(maze[i][j]=='@'&& !visit[i][j]){visit[i][j]=1; dfs(i,j);sum++;}
            }
        }
        cout<<sum<<endl;
        
    }
 
    return 0;
 
}


0 0
原创粉丝点击