您的位置:首页 > 其它

油田 Oil Deposits

2015-07-29 09:18 381 查看
油田

题目链接: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遍历
从每个‘@’格子出发,递归遍历它周围的‘@’格子。每次访问一个格子都进行标记,防止重复遍历。


#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=105;
char pic[maxn][maxn];
int m,n,d[maxn][maxn];
void dfs(int x,int y,int z)
{
if(x<0||x>=m||y<0||y>=n) return;     //格子的边界
if(d[x][y]>0||pic[x][y]!='@') return;                      //遍历过的格子和没在八连块中的格子
d[x][y]=z;                //对遍历过的格子进行标记
for(int r=-1;r<=1;r++)
for(int c=-1;c<=1;c++)
if(r!=0||c!=0)  dfs(x+r,y+c,z);
}
int main()
{
int i;
while(scanf("%d%d",&m,&n)==2&&m&&n)
{
for( i=0;i<m;i++)
cin>>pic[i];
memset(d,0,sizeof(d));
int c=0;
for( i=0;i<m;i++)
for(int j=0;j<n;j++)
if(d[i][j]==0&pic[i][j]=='@')
dfs(i,j,++c);
cout<<c<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: