1、注意字符输入
2、多组样例的时候注意初始化为0,老忘 QAQ
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn = 110;
const int INF = 0x3f3f3f3f;
char a[maxn][maxn];
int m,n;
bool inq[maxn][maxn]; //记录位置(x, y)是否已入过队
int X[8] = {0, 0, 1, -1, 1, 1, -1, -1}; //增量数组
int Y[8] = {1, -1, 0, 0, 1, -1, 1, -1};
struct NODE
{
int x,y; // 位置(x, y)
};
bool judge(int x, int y) //判断坐标(x, y)是否需要访问
{
//越界返回false
if(x>=m || x<0 || y>=n || y<0)
return false;
//当前位置为*,或(x, y)已入过队,返回false
if(a[x][y] == '*' || inq[x][y] == true)
return false;
//以上都不满足,返回true
return true;
}
//BFS函数访问位置(x, y)所在的块,将该块中所有@的inq都设置为true
void BFS(int x, int y)
{
queue<NODE> Q; //定义队列
NODE node; //临时变量(当前节点)
node.x = x;
node.y = y; //当前结点的坐标为(x,y)
Q.push(node); //将结点node入队
inq[x][y] = true; //设置(x,y)已入过队
while(!Q.empty())
{
NODE top = Q.front(); //取出队首元素
Q.pop(); //队首元素出队
for(int i=0;i<8;i++) //循环8次,得到8个相邻位置
{
int newX = top.x + X[i];
int newY = top.y + Y[i];
if(judge(newX, newY)) //如果新位置(newX,newY)需要访问
{
node.x = newX;
node.y = newY; //设置Node的坐标为(newX, newY)
Q.push(node); //将结点Node加入队列
inq[newX][newY] = true; //设置位置(newX, newY)已入过队
}
}
}
}
int main()
{
while(cin>>m>>n&&m)
{
//m行n列
for(int x=0;x<m;x++) //输入
for(int y=0;y<n;y++)
cin>>a[x][y];
memset(inq,false,sizeof(inq));
int ans = 0; //存放块数
for(int x=0;x<m;x++) //枚举每一个位置
{
for(int y=0;y<n;y++)
{
//如果元素为@,且未入过队
if(a[x][y]=='@'&&inq[x][y]==false)
{
ans++; //块数加1
BFS(x,y); //访问整个块,将该块所有@的inq都标记为true
}
}
}
printf("%d\n",ans);
}
return 0;
}