【JZOJ】家族

DescriptionDescription

一張n行的地圖
有“ ”(空格)、“*” 與小寫字母組成
*
”’與“ ”(空格)表示海
小寫字母表示島嶼
問有多少座島嶼

InputInput

第一行,一個數n
第2~n+1行,爲描述這個圖

OutputOutput

一個數,島嶼數

SampleSample InputInput
4
*zlw**pxh
l*zlwk*hx*
w*tyy**yyy
       zzl
SampleSample OutputOutput
3

思路

用BFS掃描整張圖

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int dx[5]={0,0,0,1,-1};
const int dy[5]={0,1,-1,0,0};
int A[125][225];
int Ans,m,n,l;
string s;
char c;
bool Check(int x,int y)
{
	if(x<1 || x>n || y<1 || y>m)return 0;
	if(!A[x][y])return 0;
	return 1;
}
void Bfs(int xx,int yy)
{
	queue<int>x;x.push(xx);
	queue<int>y;y.push(yy);
	while(x.size())
	{
		xx=x.front();x.pop();
		yy=y.front();y.pop();
		for(int i=1;i<=4;++i)
			if(Check(xx+dx[i],yy+dy[i]))
			{
				A[xx+dx[i]][yy+dy[i]]=0;
				x.push(xx+dx[i]);
				y.push(yy+dy[i]);
			}
	}
}
int main()
{
	freopen("family.in","r",stdin);
	freopen("family.out","w",stdout);
	scanf("%d",&n);
	getchar();
	for(int i=1;i<=n;++i)
	{
		l=0;
		c=getchar();
		while((c<'a' || c>'z') && c!='*' && c!=' ')c=getchar();
		while((c>='a' && c<='z') || c==' ' || c=='*')
		{
			if(!(c==' ' || c=='*'))A[i][++l]=1;//把是島嶼的設爲1
			else ++l;
			c=getchar();
		}
		m=max(m,l);
	}
	for(int i=1;i<=n;++i)
		for(int j=1;j<=m;++j)
			if(A[i][j])
			{
				A[i][j]=0;
				Bfs(i,j);//BFS
				Ans++;
			}
	printf("%d\n",Ans);
	fclose(stdin);
	fclose(stdout);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章