这道题用bfs和和dfs都差不多,有一点我觉得很有必要说一下,由于这个错我调试了好半天!!,就是在输入的时候可以有多个空格,但我以为只有一个空格!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct ff
{
int x;
int y;
}ff[100000];
int m,n,map[105][105];//map[i][j]为标记数组
int dit[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
char ch;
int h1,h2,sum; //sum:oil的个数
int main()
{
int i,j,p,vx,vy;
while(scanf("%d %d",&m,&n)!=EOF&&m)
{
//getchar();//过滤换行符
memset(map,0,sizeof(map));
sum=0;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
while(ch=getchar(),ch!='*'&&ch!='@');//在此要注意有多个空格
//printf("%d %d c=%c\n",i,j,str[i][j]);
if(ch=='*')map[i][j]=1;
}
getchar();
}
//for(i=1;i<=m;i++)
//{
//for(j=1;j<=n;j++)
//printf("%c ",str[i][j]);
//printf("\n");
//}
//for(i=1;i<=m;i++)
//{
//for(j=1;j<=n;j++)
//printf("%d ",map[i][j]);
//printf("\n");
//}
for(i=1;i<=m;i++) //bfs
for(j=1;j<=n;j++)
{
if(!map[i][j])
{
//printf("%d %d\n",i,j);
//printf("------\n");
sum++;
h1=0;
h2=1;
ff[0].x=i;
ff[0].y=j;
while(h1<h2)
{
for(p=0;p<8;p++)
{
vx=ff[h1].x+dit[p][0];
vy=ff[h1].y+dit[p][1];
if(vx>=1&&vx<=m&&vy>=1&&vy<=n&&!map[vx][vy])
{
//printf("&&&&%d %d\n",vx,vy);
map[vx][vy]=1;
ff[h2].x=vx;
ff[h2++].y=vy;
}
} //for
h1++;
}//while
}//if
}//for
printf("%d\n",sum);
}//while
system("pause");
return 0;
}