poj 2386 Lake Counting

来源:互联网 发布:永久域名购买 编辑:程序博客网 时间:2024/05/01 23:16

poj   2386   Lake Counting                           题目链接:http://poj.org/problem?id=2386

题目大意:数湖。

题目分析:求一个非连通图里有几个连通部分,用BFS、DFS都能过,这里我用的是BFS。

code:

#include<cstdio>#include<cstring>#include<queue>using namespace std;int m,n,dir[8][2]={1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,1,-1,-1};char g[110][110];struct node{int x,y;};queue<node>q;bool judge(int x,int y){return x<m&&y<n&&x>=0&&y>=0&&g[x][y]=='W';}void bfs(int x,int y){node first,next;first.x=x,first.y=y;q.push(first);while(!q.empty()){first=q.front();q.pop();g[first.x][first.y]='.';for(int i=0;i<8;i++){next.x=first.x+dir[i][0];next.y=first.y+dir[i][1];if(judge(next.x,next.y)){q.push(next);g[next.x][next.y]='.';}}}}int cgcounting(){//connected graph countingint ans=n*m;for(int i=0;i<m;i++){for(int j=0;j<n;j++){if(g[i][j]=='W')bfs(i,j);else ans--;}}return ans;}int main(){int i,j,k;while(scanf("%d%d",&m,&n)!=EOF){memset(g,0,sizeof(g));for(i=0;i<m;i++){scanf("%s",g[i]);}printf("%d\n",cgcounting());}return 0;}
PS:重做BFS,居然M.L.E死了抓狂……究其原因,是visit记录放的地方不对。一开始我写的是队首元素出队时改visit,结果MLE,冷静下来之后发现错误,改成入队写visit。




0 0