hdu 1241 Oil Deposits
http://acm.hdu.edu.cn/showproblem.php?pid=1241
今天第一次做DFS的题,虽然这道题目也可以用BFS,不过我还是觉得DFS简单,所以就用DFS,把八个方向的点都置为0,只剩一个2,所以只要查找2的个数即可。。
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int hash[120][120];
void DFS(int x,int y)
{
if(x<0||y<0||(hash[x][y]!=2))
return ;
if(hash[x][y]==2)
{
hash[x][y]=0;
DFS( x-1,y-1 );
DFS( x-1,y );
DFS( x-1,y+1 );
DFS( x,y-1 );
DFS( x,y+1 );
DFS( x+1,y-1 );
DFS( x+1,y );
DFS( x+1,y+1 );
}
}
int main()
{
char s[105];
int m,n,c;
while(scanf("%d%d",&m,&n),m&&n)
{
c=0;
memset(hash,0,sizeof(hash));
for(int i=0;i<m;++i)
{
scanf("%s",s);
for(int j=0;j<n;++j)
if(s[j]=='*')
hash[i][j]=1;
else
hash[i][j]=2;
}
for(int i=0;i<m;++i)
for(int j=0;j<n;++j)
{
if(hash[i][j]==2)
{
c++;
DFS(i,j);
}
}
printf("%d\n",c);
}
// system("pause");
return 0;
}