572 - Oil Deposits

来源:互联网 发布:淘宝回收手机被骗了 编辑:程序博客网 时间:2024/05/16 10:19



  Oil Deposits 

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 \le m \le 100$ and $1 \le n \le 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>#include<string.h>#include<queue>#define  MAX 102using namespace std;void init_grap(int (*G)[MAX],int row,int col){//初始化图,用0代表*,1代表@,并给原图包裹一圈0int r=1,c=1;char flag;while(cin>>flag){if(flag=='*')G[r][c++]=0;else if(flag=='@') G[r][c++]=1;if(c==col+1) {++r;c=1;}if(r==row+1) break;}}int visited[MAX][MAX];void DFS(int (*G)[MAX],int r,int c){if(visited[r][c] || !G[r][c]) return ;//已经访问或者(r,c)位置没有油visited[r][c]=1;    DFS(G,r-1,c-1);DFS(G,r-1,c);DFS(G,r-1,c+1);DFS(G,r,c-1);               DFS(G,r,c+1);DFS(G,r+1,c-1);DFS(G,r+1,c);DFS(G,r+1,c+1);}void print_grap(int (*G)[MAX],int row,int col){//输出图,测试用   for(int r=0;r<row+2;++r){   for(int c=0;c<col+2;++c){       cout<<G[r][c]<<" ";   }   cout<<endl;   }}int main(){int row,col;while(cin>>row>>col){   if(!row && !col) break;   int G[MAX][MAX];   memset(G,0,sizeof(G));   memset(visited,0,sizeof(visited));   init_grap(G,row,col);   int count=0;   for(int i=1;i<=row;++i){   for(int j=1;j<=col;++j){      if(!visited[i][j] && G[i][j]){  ++count;  DFS(G,i,j);  }   }   }   cout<<count<<endl;  // print_grap(G,row,col);}    return 0;}


0 0
原创粉丝点击