题目描述:
小猫在研究网格图。
小猫在研究联通性。
给定一张N×M的网格图,只含字符0和1,问1形成的联通块有多少个。
两个1是联通的,当且仅当其中一个位于另一个的上、下、左、右四个方向之一
输入描述:
第一行一个正整数T,表示数据组数。
每组数据的第一行两个正整数N,M,表示矩阵的长和宽。
接下来N行,每行M个字符0或1。
输出描述:
一行一个整数表示答案。
输入:
3
1 2
1 3
输出:
1
题意:
题目描述
题解:
直接爆搜
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int dir[10][10] = {{0,1},{-1,0},{0,-1},{1,0}};
const int maxn = 105;
char s[maxn][maxn];
int n,m;
void dfs(int x,int y){
s[x][y] = '0';
for(int i = 0; i < 4; i ++){
int dx = x + dir[i][0];
int dy = y + dir[i][1];
if(dx >= 0 && dx < n && dy >= 0 && dy < m && s[dx][dy] == '1'){
dfs(dx,dy);
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i ++){
scanf("%s",s[i]);
}
int ans = 0;
for(int i = 0; i < n; i ++){
for(int j = 0; j < m; j ++){
if(s[i][j] == '1'){
dfs(i,j);
ans ++;
}
}
}
printf("%d\n",ans);
}
return 0;
}