2023年第14届蓝桥杯大赛软件赛省赛 C/C++ 大学 B 组 试题 F: 岛屿个数(15)

b2d51a0b82b441e6b16fb1769754df84.jpg

 14ed2a9fb2d24ec8bde5e1dc78c33afa.jpg

 样例输入
2
5 5
01111
11001
10101
10001
11111
5 6
111111
100001
010101
100001
111111
样例输出
1
3

a6991cd60ada44ddbb51f1cf96e06aa0.jpg

解题思路
从(0,0)(0,0)(0,0)开始染色,把遇到的0全部染成2,这样没染色的部分,一定为环,接着再搜索环的个数即可。

注意:开始染色的时候,可能有斜角,得使用八向搜索;搜索环的时候则用四向搜索。

参考代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 5e1 + 5;
int T, m, n;
char g[N][N];
int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1};
int dy[8] = {1, -1, 0, 0, -1, 1, 1, -1};
int ans;
struct point {
    int x, y;
};
void bfs1() {
    queue<point>q;
    g[0][0] = '2';
    q.push({0, 0});
    while (!q.empty()) {
        point now = q.front();
        q.pop();
        for (int i = 0; i < 8; i++) {
            int tx = now.x + dx[i];
            int ty = now.y + dy[i];
            if (tx >= 0 && ty >= 0 && tx <= m + 1 && ty <= n + 1) {
                if (g[tx][ty] == '0') {
                    g[tx][ty] = '2';
                    q.push({tx, ty});
                }
            }
        }
    }
}
void bfs2(int x, int y) {
    queue<point>q;
    g[x][y] = '2';
    q.push({x, y});
    while (!q.empty()) {
        point now = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int tx = now.x + dx[i];
            int ty = now.y + dy[i];
            if (tx >= 1 && ty >= 1 && tx <= m && ty <= n) {
                if (g[tx][ty] == '0' || g[tx][ty] == '1') {
                    g[tx][ty] = '2';
                    q.push({tx, ty});
                }
            }
        }
    }
}
int main() {
    cin >> T;
    while (T--) {
        cin >> m >> n;
        memset(g, '0', sizeof(g));
        ans = 0;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                cin >> g[i][j];
            }
        }
        bfs1();
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (g[i][j] == '1') {
                    ans++;
                    bfs2(i, j);
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}

bb5c80a6a30446e48507f45542832987.png

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值