转载请注明出处:忆梦http://blog.csdn.net/fjy4328286/article/details/9427393
题目大意:有N*M的矩阵稻田,'W'表示有积水的地方, '.'表示是干旱的地方,问稻田内一共有多少块积水,根据样例很容易得出,积水是8个方向任一方向相连即可。
题解:直接广搜,遍历一下,用vis数组标记已经搜到了的,搜到了的就vis = 1
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define N 105
using namespace std;
int x[] = {-1,0,1,1,1,0,-1,-1};
int y[] = {1,1,1,0,-1,-1,-1,0};
bool vis[N][N];
char map[N][N];
int n, m;
typedef struct Node
{
int x, y;
};
queue<Node>Q;
void BFS()
{
Node temp, s;
while(!Q.empty())
{
s = Q.front();
Q.pop();
temp.x = s.x;
temp.y = s.y;
for(int i = 0; i < 8; i++)
{
int a = temp.x + x[i];
int b = temp.y + y[i];
if(a >= 0 && a< n && b >= 0 && b < m && !vis[a][b] && map[a][b] == 'W')
{
vis[a][b] = 1;
s.x = a;
s.y = b;
Q.push(s);
}
}
}
}
int main ()
{
Node temp;
int i, j;
scanf("%d %d", &n ,&m);
for(i = 0; i < n; i++)
scanf("%s", map[i]);
memset(vis, 0, sizeof(vis));
int ans = 0;
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
{
if(map[i][j] == 'W' && !vis[i][j])
{
vis[i][j] = 1;
temp.x = i;
temp.y = j;
Q.push(temp);
BFS();
ans++;
}
}
printf("%d\n", ans);
return 0;
}