水池数目
题目
校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地图上仅标识了此处是否是水池,现在,你的任务来了,请用计算机算出该地图中共有几个水池。
输入
第一行输入一个整数N,表示共有N组测试数据
每一组数据都是先输入该地图的行数n(0<n<100)与列数m(0<m<100),然后,输入接下来的m行每行输入n个数,表示此处有水还是没水(1表示此处是水池,0表示此处是地面)
输出
输出该地图中水池的个数。
要注意,每个水池的旁边(上下左右四个位置)如果还是水池的话的话,它们可以看做是同一个水池。
思路小导
本题不管是深度搜索还是宽度搜索都能够完成,重点是在于搜索套路与细节处理,此处我应用的是深度搜索
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define endl '\n'
using ll=long long;
const size_t maxn = 101;
int a[maxn][maxn], book[maxn][maxn];//定义要检索的图(二维数组a),和标记数组book保证每个元素不被重复访问
int fx[4][2] = {{0, 1},
{0, -1},
{1, 0},
{-1, 0}};//定义方向数组,可移动的方位上下左右
void dfs(int x, int y) {
book[x][y] = 1;
for (int i = 0; i < 4; i++) {
int nx = x + fx[i][0];
int ny = y + fx[i][1];
if (nx < 0 || nx >= m || ny < 0 || ny >= n || book[nx][ny] || a[nx][ny] == 0)continue;
dfs(nx, ny);
}
}//深搜
int count() {//计数
int area = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (book[i][j])continue;
if (a[i][j] == 0)continue;
dfs(i, j);
++area;
}
}
return area;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T;
cin >> T;
while (T--) {
memset(book, 0, sizeof(book));//对book数组都初始化为0
cin >> m >> n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
}
}
int c = count();//输出所标记区域数即水池数目
cout << c << endl;
}
return 0;
}