搜索专题训练 E - 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 <= 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. 

样例输入
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0

Sample Output

0
1
2
2

题解

BFS
 1 #include <iostream>
 2 #include <queue>
 3 
 4 using namespace std;
 5 int dir[8][2]= {{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};
 6 struct node{
 7     int x,y;
 8 }t,a,p;
 9 
10 int n,m;
11 char s[105][105];
12 void bfs(int u,int v){
13     queue<node>q;
14     while(!q.empty()){
15         q.pop();
16     }
17     t.x=u;
18     t.y=v;
19     q.push(t);
20     while(!q.empty()){
21         a=q.front();
22         q.pop();
23         for(int i=0; i<8; i++)
24         {
25             p.x=a.x+dir[i][0];
26             p.y=a.y+dir[i][1];
27             if(p.x>=0&&p.x<m&&p.y>=0&&p.y<n&&s[p.x][p.y]=='@'){
28                 s[p.x][p.y]='*';
29                 q.push(p);
30             }
31         }
32     }
33 }
34 int main(){
35     while(cin>>m>>n&&m!=0){
36         int sum=0;
37        for(int i=0;i<m;i++){
38             for(int j=0;j<n; j++){
39                 cin>>s[i][j];
40             }
41         }
42         for(int i=0;i<m;i++){
43             for(int j=0;j<n;j++){
44                 if(s[i][j]=='@'){
45                     s[i][j]='*';
46                     bfs(i,j);
47                     sum++;
48                 }
49             }
50         }
51         cout<<sum<<endl;
52     }
53     return 0;
54 }

 






上一篇:HDU 1241 Oil Deposits(经典DFS)


下一篇:数据湖(Data Lake)-剑指下一代数据仓库