BNUOJ 1038 Flowers(BFS),bnuojbfs
FlowersTime Limit: 1000msMemory Limit: 65535KB64-bit integer IO format: %lld Java class name: MainPrev Submit Status Statistics Discuss Next春天到了,師大的園丁們又開始忙碌起來了.
京師廣場上有一塊空地,邊界圍成了一個多邊形,內部被劃分成一格一格的.園丁們想在這個多邊形內的每一格內種植一些花.
現在請你幫忙計算一下一共最多可以種多少花.
廣場用一個M*N的字元數組表示,"."和"*"代表一個方格,其中"*"代表空地的邊界,"."是空格,只有邊界內部的空格才能用於種花.
一個空格位於邊界內部,若且唯若由該點出發只允許向上、下、左、右四個方向移動,最終都會遇到邊界。
例如下面就是一個6*7的廣場
.......
..***..
..*..*.
..*..*.
...**..
.......
種花方案如下(數字代表的地方)
.......
..***..
..*12*.
..*34*.
...**..
.......
Input輸入資料第一行是M和N(M和N不超過100),代表有廣場的大小
接下來就是一個M*N的字元矩陣,是廣場的表示Output對應於輸入資料,輸出一個整數,給出輸入的情形能夠種的花數目.Sample Input
Sample Input16 7.........***....*..*...*..*....**.........Sample Input25 7.........***....*.*....***.........
Sample Output
Sample Output14Sample Output21
Source第七屆北京師範大學程式設計競賽熱身賽第四場
#include<stdio.h>#include<queue>#include<string.h>using namespace std;const int N = 105 ;struct node{ int x,y;};char mapt[N][N];int vist[N][N],n,m;int dir[4][2]={0,1,0,-1,1,0,-1,0};int bfs(int x,int y){ queue<node>q; node now,pre; int ans=1,flag=1; vist[x][y]=1; now.x=x; now.y=y; q.push(now); while(!q.empty()) { pre=q.front(); q.pop(); for(int e=0; e<4; e++) { now.x=pre.x+dir[e][0]; now.y=pre.y+dir[e][1]; if(now.x<0||now.x>=n||now.y<0||now.y>=m) { flag=0; continue; } if(!vist[now.x][now.y]&&mapt[now.x][now.y]=='.') { vist[now.x][now.y]=1; ans++; q.push(now); } } } if(flag==0) ans=0; return ans;}int main(){ //int n,m; while(scanf("%d%d",&n,&m)>0) { for(int i=0; i<n; i++) scanf("%s",mapt[i]); int ans=0; memset(vist,0,sizeof(vist)); for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(!vist[i][j]&&mapt[i][j]=='.') ans+=bfs(i,j); printf("%d\n",ans); }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。