题目很简单,用DFS也可以写。
只是先熟悉一下BFS的思想。
AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define MAXN 103
struct node{
int i, j;
};
int n, m,ship[MAXN][MAXN],vis[MAXN][MAXN];
node a;
queue<node> q;
void bfs(int i,int j){
if (ship[i][j] == 0 || vis[i][j] == 1){
return;
}
vis[i][j] = 1;
if (ship[i - 1][j] == 1){
a.i = i - 1;
a.j = j;
q.push(a);
}
if (ship[i + 1][j] == 1){
a.i = i + 1;
a.j = j;
q.push(a);
}
if (ship[i][j-1] == 1){
a.i = i;
a.j = j - 1;
q.push(a);
}
if (ship[i][j + 1] == 1){
a.i = i;
a.j = j + 1;
q.push(a);
}
}
int main(){
// freopen("TestDate.txt", "r", stdin);
int tn,i,j,vist;
char ch;
cin >> tn;
while (tn--){
memset(ship, 0, sizeof(ship));
memset(vis, 0, sizeof(vis));
cin >> n >> m;
for (i = 1; i <= n; i++){
for (j = 1; j <= m; j++){
cin >> ch;
if (ch == '#'){
ship[i][j] = 1;
}
else{
ship[i][j] = 0;
}
}
}
vist = 0;
for (i = 1; i <= n; i++){
for (j = 1; j <= m; j++){
if (ship[i][j] == 1 && vis[i][j] == 0){
bfs(i, j);
while (!q.empty()){
a = q.front();
q.pop();
bfs(a.i, a.j);
}
vist++;
}
}
}
cout << vist << endl;
}
return 0;
}