水题。BFS。
题目连接:http://poj.org/problem?id=2386
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;
int n,m;
int map[102][102];
int visited[102][102];
int disx[8] = {0,1,1,1,0,-1,-1,-1};
int disy[8] = {1,1,0,-1,-1,-1,0,1};
struct Point
{
int x;
int y;
};
int bfs(int x,int y)
{
queue<Point> q;
Point temp,nex;
nex.x = x;
nex.y = y;
q.push(nex);
visited[x][y] = 1;
while(!q.empty())
{
temp = q.front();
q.pop();
for(int i=0; i<8; i++)
{
int tempx = temp.x + disx[i];
int tempy = temp.y + disy[i];
if(tempx>=0 && tempx<n && tempy>=0 && tempy<m )
{
if(visited[tempx][tempy] == 0 && map[tempx][tempy] == 1)
{
nex.x = tempx;
nex.y = tempy;
q.push(nex);
visited[tempx][tempy] = 1;
}
}
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
scanf(" %d %d",&n,&m);
memset(map,0,sizeof(map));
memset(visited,0,sizeof(visited));
char c;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
scanf(" %c",&c);
if(c == 'W')
{
map[i][j] = 1;
}
else if(c == '.')
{
map[i][j] = 0;
}
}
}
int ans = 0;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(map[i][j] == 1 && visited[i][j] == 0)
{
bfs(i,j);
ans++;
}
}
}
printf("%d\n",ans);
return 0;
}