注解
1、从第一个点,到最后一个点,进行广度优先遍历BFS。
2、遍历八个方向:上下左右,右上,右下,左上,左下。
代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 101;
int M, N;
int visit[MAXN][MAXN];
char ch[MAXN][MAXN];
int dirx[8] = {0, 0, 1, 1, 1, -1, -1, -1};
int diry[8] = {1, -1, 0, 1, -1, 0, 1, -1};
struct Node {
int x;
int y;
};
void BFS(int x, int y) {
queue<Node> q;
Node node;
node.x = x;
node.y = y;
visit[x][y] = 1;
q.push(node);
while(q.size()>0) {
Node top = q.front();
q.pop();
for(int i=0; i<8; i++) {
int tmpX = top.x + dirx[i];
int tmpY = top.y + diry[i];
if(tmpX>=0 && tmpX<M && tmpY>=0 && tmpY<N && !visit[tmpX][tmpY] && ch[tmpX][tmpY]=='@') {
visit[tmpX][tmpY] = 1;
Node tmpNode;
tmpNode.x = tmpX;
tmpNode.y = tmpY;
q.push(tmpNode);
}
}
}
}
int main() {
scanf("%d %d", &M, &N);
getchar();
while(M || N) {
memset(visit, 0, sizeof(visit));
memset(ch, 0, sizeof(ch));
for(int i=0; i<M; i++) {
for(int j=0; j<N+1; j++) {
ch[i][j] = getchar();
}
}
int cnt = 0;
for(int i=0; i<M; i++) {
for(int j=0; j<N; j++) {
if(!visit[i][j] && ch[i][j]=='@') {
visit[i][j] = 1;
BFS(i, j);
cnt++;
}
}
}
printf("%d\n", cnt);
scanf("%d %d", &M, &N);
getchar();
}
return 0;
}