POJ2386 Lake Counting
/*BFS
0MS 592K
*/
#include <stdio.h>
#include <utility>//pair<>
#include <queue>
#define x first
#define y second
using namespace std;
int M,N;
const int MAX=105;
const int INF=0x3f3f3f3f;
char m[MAX][MAX];
int next[8][2]={1,0,0,1,-1,0,0,-1,1,1,-1,-1,1,-1,-1,1};
typedef pair<int,int>Point;
void BFS(int &ax,int &ay)
{
queue<Point>Q;
Point a(ax,ay);
Q.push(a);
m[a.x][a.y]='.';
while (!Q.empty())
{
Point now,then;
now=Q.front();
Q.pop();
for (int k=0;k<8;k++)
{
then=now;
then.x+=next[k][0];
then.y+=next[k][1];
if (then.x<0||then.y<0||then.x>=M||then.y>=N||m[then.x][then.y]=='.') continue;
Q.push(then);
m[then.x][then.y]='.';
}
}
}
int main ()
{
int ans=0;
scanf ("%d%d",&M,&N);
for (int i=0;i<M;i++)
scanf ("%s",m[i]);
for (int i=0;i<M;i++)
for (int k=0;k<N;k++)
if (m[i][k]=='W')
{
BFS(i,k);
ans++;
}
printf ("%d\n",ans);
return 0;
}
本文介绍了一个使用广度优先搜索(BFS)算法解决的编程问题——POJ2386湖面计数。通过详细的代码示例,展示了如何遍历二维数组来计算湖泊的数量,并解释了BFS算法的具体实现过程。
457

被折叠的 条评论
为什么被折叠?



