Tip 1
Enter a line of strings with spaces, use getline instead of gets
string asd;
getline(cin, asd);
Tip 2
When inputting two integers n m first, and then inputting characters with no spaces in the middle of n rows and m columns
Use char array to define two-dimensional matrix, use cin>> to input
Tip 3
When inputting an integer n first, and then inputting n lines of strings that may contain spaces, you need to add two getchar() after inputting n, otherwise an error will occur.
Example: P1767 family
#include <bits/stdc++.h>
using namespace std;
int n, m=200, len, ans;
int mx[5]={0, -1, 1, 0, 0};
int my[5]={0, 0, 0, -1, 1};
string s;
char a[110][210];
bool vis[110][210];
queue<int> qx, qy;
void bfs(int x, int y)
{
int nx, ny;
qx.push(x);
qy.push(y);
while(!qx.empty()){
x=qx.front();
y=qy.front();
qx.pop();
qy.pop();
for(int i=1; i<=4; ++i){
nx=x+mx[i];
ny=y+my[i];
if(nx>=1 && nx<=n && ny>=1 && ny<=m && !vis[nx][ny] && a[nx][ny]>='a' && a[nx][ny]<='z'){
vis[nx][ny]=true;
qx.push(nx);
qy.push(ny);
}
}
}
}
int main()
{
scanf("%d", &n);
getchar();
getchar();
for(int i=1; i<=n; ++i){
getline(cin, s);
len=s.length();
for(int j=1; j<=len; ++j){
a[i][j]=s[j-1];
}
for(int j=len+1; j<=m; ++j){
a[i][j]=' ';
}
}
for(int i=1; i<=n; ++i){
for(int j=1; j<=m; ++j){
if(a[i][j]>='a' && a[i][j]<='z' && !vis[i][j]){
ans++;
vis[i][j]=true;
bfs(i, j);
}
}
}
printf("%d", ans);
return 0;
}