HDU 2952 Counting Sheep

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2952


思路:简单搜索,我用DFS做


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char sheep[103][103];
int n,m;
void Init()
{
   int i;
   for(i=0;i<=n+1;i++) {sheep[i][0]='.';sheep[i][m+1]='.';}
   for(i=0;i<=m+1;i++) {sheep[0][i]='.';sheep[n+1][i]='.';}
}
void dfs(int x,int y)
{
   sheep[x][y]='.';
   if(sheep[x-1][y]=='#') dfs(x-1,y);
   if(sheep[x+1][y]=='#') dfs(x+1,y);
   if(sheep[x][y-1]=='#') dfs(x,y-1);
   if(sheep[x][y+1]=='#') dfs(x,y+1);
}
int main()
{
   int T,i,j,ans;
   scanf("%d",&T);
   while(T--)
   {
      scanf("%d%d",&n,&m);
	  Init();
	  for(i=1;i<=n;i++)
	  {
	     getchar();
		 for(j=1;j<=m;j++)
		   scanf("%c",&sheep[i][j]);
	  }
       ans=0;
	   for(i=1;i<=n;i++)
		   for(j=1;j<=m;j++)
		      if(sheep[i][j]=='#')
			  {
			     ans++;
				 dfs(i,j);
			  }
		printf("%d\n",ans);
   }
   return 0;
}


你可能感兴趣的:(c)