题目描述
从红魔馆的大门往里面看就可以看到一个大花园。园内不止种花,而且还种植了各种魔法药材供帕秋莉使用。芙兰对花园里的药材感到好奇,于是她就问红魔馆的门番兼园丁花园里有多少种不同的药材。但是红师傅在看门的时候不是在睡觉就是在睡觉!她只知道各种药材被分割开来,互不相邻。现在你从帕琪那里拿到了花园的地图,药材用小写字母表示,其他花草用'*'表示,空地用空格表示,你能替那个门番回答二小姐的问题吗?
顺便一提,同种药材也有优劣之分,帕琪可能会用不同的小写字母表示同一种药材,不同种类的药材一定是被其他花草或是空地分割开的。
输入
输入一个正整数n表示地图有n行
接着n行每行有一个字符串,包含小写字母,空格和'*'三种字符,意义如题面。
注意:每行都有可能以若干空格开头,且每行长度也不一定相同!
输出
一个正整数,表示药材的种类数。
样例输入 Copy
5 abca bbb* * * * abc e ccc
样例输出 Copy
3
提示
于10%的数据:n≤10,字符串长度≤10;
对于30%的数据: n≤100,字符串长度≤200;
对于100%的数据: n≤1000,字符串长度≤400;
#include <bits/stdc++.h>
using namespace std;
int n;
string s[2100];
char a[2100][2100];
int book[2100][2100];
int head = 1;
int tail = 1;
int len;
typedef struct ac {
int a;
int b;
} QUE;
QUE que[400008];
void bfs(int x, int y)
{
book[x][y]=1;
que[tail].a = x;
que[tail].b = y;
tail++;
// head=1;tail=2;
int next[4][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int tx, ty;
int i, j;
while (head < tail) {
for (i = 0; i < 4; i++) {
tx = que[head].a + next[i][0];
ty = que[head].b + next[i][1];
if(tx<1||tx>n||ty<1||ty>len)continue;
if (a[tx][ty] >= 97 && a[tx][ty] <= 122 && book[tx][ty] == 0) {
book[tx][ty] = 1;
que[tail].a = tx;
que[tail].b = ty;
tail++;
}
}
head++;
}
return ;
}
int main()
{
int res=0;
// int n;
cin >> n;
getline(cin, s[0]);
int i, j;
for (i = 1; i <= n; i++) { //每行字符数不同,找最大的作为整体边界
getline(cin, s[i]);
len = max(len, (int)s[i].size());
for (j = 0; j < (int)s[i].size(); j++) {
if (s[i][j] >= 97 && s[i][j] <= 122) {
a[i][j + 1] = s[i][j];
}
}
}
for (i = 1; i <= n; i++) { //找寻可能存在的连通块
for (j = 1; j <= len; j++) {
if (a[i][j] >= 97 && a[i][j] <= 122 && book[i][j] == 0) {
res++;
bfs(i, j);
}
}
}
cout<<res<<endl;
return 0;
}