油田 Oil Deposits

油田 

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=84562#problem/L

 题意:

    输入一个m行n列的字符矩形,统计字符“@”组成多少个八连块。如果两个字符“@”所在的格子相邻(横,竖或者对角线方向),

就说题目属于同一个八连块。

样例:

Sample Input

1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5 
****@
*@@*@
*@**@
@@@*@
@@**@
0 0

Sample Output

0
1
2
2


分析:
用dfs遍历
从每个‘@’格子出发,递归遍历它周围的‘@’格子。每次访问一个格子都进行标记,防止重复遍历。
 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 const int maxn=105;
 5 char pic[maxn][maxn];
 6 int m,n,d[maxn][maxn];
 7 void dfs(int x,int y,int z)
 8 {
 9 if(x<0||x>=m||y<0||y>=n) return;     //格子的边界
10 if(d[x][y]>0||pic[x][y]!='@') return;                      //遍历过的格子和没在八连块中的格子
11  d[x][y]=z;                //对遍历过的格子进行标记
12    for(int r=-1;r<=1;r++)
13        for(int c=-1;c<=1;c++)
14            if(r!=0||c!=0)  dfs(x+r,y+c,z);
15 }
16 int main()
17 {
18     int i;
19     while(scanf("%d%d",&m,&n)==2&&m&&n)
20     {
21     for( i=0;i<m;i++)
22         cin>>pic[i];
23     memset(d,0,sizeof(d));
24     int c=0;
25     for( i=0;i<m;i++)
26         for(int j=0;j<n;j++)
27             if(d[i][j]==0&pic[i][j]=='@')  
28                 dfs(i,j,++c);
29             cout<<c<<endl;
30     }
31 return 0;
32 }
原文地址:https://www.cnblogs.com/fenhong/p/4685005.html