HUAS Summer Trainning #3 L

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

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

0
1
2
2
题目大意:给你个M*N的矩阵,每个单位要么是‘*’(无石油)要么是‘@’(有石油),
要你找有多少个不相连的石油。
题目思路:这个相当于是找连通块问题,用循环找到的第一个@,然后再向它的八方查找,再找到一个@,
又向它的八方遍历,直到八方都找不到@,那么这就是第一个连通块,(用数组把他们都标记为1),
其他的也是这样找直到把这个矩阵遍历完。(这也就是种子填补法)
代码:
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 const int maxn=100+5;
 6 char a[maxn][maxn];
 7 int m,n,b[maxn][maxn];
 8 void dfs(int r,int c,int id)
 9 {
10     if(r<0||r>=m||c<0||c>=n)
11         return;
12     if(b[r][c]>0||a[r][c]!='@')
13         return;
14     b[r][c]=id;
15     for(int dr=-1;dr<=1;dr++)
16         for(int dc=-1;dc<=1;dc++)
17             if(dr!=0||dc!=0)
18                 dfs(r+dr,c+dc,id);
19 }
20 int main()
21 {
22     int i,j;
23     while(cin>>m>>n&&m&&n)
24     {
25         for(i=0;i<m;i++)
26             cin>>a[i];
27         memset(b,0,sizeof(b));
28         int cnt=0;
29         for(i=0;i<m;i++)
30         {
31             for(j=0;j<n;j++)
32                 if(b[i][j]==0&&a[i][j]=='@')
33                     dfs(i,j,++cnt);
34         }
35         
36         cout<<cnt<<endl;
37     }
38     return 0;
39 }

 


posted on 2015-08-02 18:59  最爱剪刀手  阅读(104)  评论(0编辑  收藏  举报