蓝桥杯每日一题2023.9.11

蓝桥杯2023年第十四届省赛真题-岛屿个数 - C语言网 (dotcpp.com)

题目描述

小蓝得到了一副大小为 M × N 的格子地图,可以将其视作一个只包含字符‘0’(代表海水)和 ‘1’(代表陆地)的二维数组,地图之外可以视作全部是海水,每个岛屿由在上/下/左/右四个方向上相邻的 ‘1’ 相连接而形成。

在岛屿 A 所占据的格子中,如果可以从中选出 k 个不同的格子,使得他们的坐标能够组成一个这样的排列:(x0, y0),(x1, y1), . . . ,(xk−1, yk−1),其中(x(i+1)%k , y(i+1)%k) 是由 (xi , yi) 通过上/下/左/右移动一次得来的 (0 ≤ i ≤ k − 1),

此时这 k 个格子就构成了一个 “环”。如果另一个岛屿 B 所占据的格子全部位于这个 “环” 内部,此时我们将岛屿 B 视作是岛屿 A 的子岛屿。若 B 是 A 的子岛屿,C 又是 B 的子岛屿,那 C 也是 A 的子岛屿。

请问这个地图上共有多少个岛屿?在进行统计时不需要统计子岛屿的数目。

分析

对于这个问题我们可以思考:什么是真正需要统计的岛屿?那就是与最外面的海可以直接相连的岛屿,我们可以从最外面的海中进行dfs,如果是‘0’说明此处依旧是海,可以将其标记为已经访问过,如果是‘1’说明此为岛屿,可以将这个岛屿进行另一个bfs,将这些遍历过的岛屿也设置为true,这些连海岛屿的个数即为最终的答案

#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
typedef pair<int, int> PII;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int dx1[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy1[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
int n, m, t, cnt;
bool v[N][N];
char g[N][N];
queue<PII> q;
void bfs(int x, int y)
{
	queue<PII> q;
	q.push({x, y});
	v[x][y] = true;
	while(q.size())
	{
		auto t = q.front();
		q.pop();
		for(int i = 0; i < 4; i ++)
		{
			int a = t.first + dx[i];
			int b = t.second + dy[i];
			if(a >= 0 && a <= n + 1 && b >= 0 && b <= m + 1 && g[a][b] == '1' && !v[a][b])
			{
				v[a][b] = true;
				q.push({a, b});
			}
		}
	}
}
void bfs1(int x, int y)
{
	queue<PII>q;
	q.push({x, y});
	v[x][y] = true;
	while(q.size())
	{
		auto t = q.front();
		q.pop();
		for(int i = 0; i < 8; i ++)
		{
			int a = t.first + dx1[i];
			int b = t.second + dy1[i];
			if(a >= 0 && a <= n + 1 && b >= 0 && b <= m + 1 && !v[a][b])
			{
				if(g[a][b] == '1')
				{
					cnt ++;
					bfs(a, b);
				}
				else
				{
					q.push({a, b});
					v[a][b] = true;
				}
			}
		}
	}
}
void solve()
{
	cnt = 0;
	cin >> n >> m;
	memset(g, '0', sizeof g);
	memset(v, 0, sizeof v);
	for(int i = 1; i <= n; i ++)
	{
		for(int j = 1; j <= m; j ++)
		{
			cin >> g[i][j];
		}
	}
	bfs1(0, 0);
	cout << cnt << '\n';
}
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> t;
	while(t --)
	{
		solve();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_75087931/article/details/132812763