版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xj13821328013/article/details/77914390
一道很简单的搜索题目,而且没有返回条件,只要注意将图设为全局变量,边搜边改变符号即可,不过最令我抓狂的是将main()函数中的while(!Q.empty())写成while(Q.empty())
调试了将近一小时= =教训十分深刻
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
int m,n;
char ma[110][110];
int go[8][2]={0,1,0,-1,1,0,-1,0,1,1,-1,-1,1,-1,-1,1};
//bool mark[110][110];
struct node
{
int x,y;
};
queue<node> Q;
int BFS(int x,int y)
{
node tmp;
tmp.x=x;tmp.y=y;
Q.push(tmp);
ma[x][y]='*';
while(!Q.empty())
{
node temp;
temp=Q.front();
Q.pop();
for(int i=0; i<8; i++)
{
int tx=temp.x+go[i][0];
int ty=temp.y+go[i][1];
if(tx>=0&&tx<m&&ty>=0&&ty<n&&ma[tx][ty]=='@')
{
ma[tx][ty]='*';
node tp;
tp.x=tx;tp.y=ty;
//printf("%d %d\n",tx,ty);
Q.push(tp);
// printf("1\n");
}
}
}
return 0;
}
int main()
{
while(~scanf("%d %d",&m,&n)&&(n||m))
{
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
cin>>ma[i][j];
}
}
//memset(mark,false,sizeof(mark));
while(!Q.empty())
{
Q.pop();
}
int ans=0;
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(ma[i][j]=='@')
{
// ma[i][j]='*';
BFS(i,j);
/* printf("\n");
for(int p=0; p<m; p++)
{
for(int q=0; q<n; q++)
{
printf("%c",ma[p][q]);
}
printf("\n");
}*/
// printf("%d %d -1\n",i,j);
ans++;
}
}
}
printf("%d\n",ans);
}
return 0;
}