
You are mapping a faraway planet using a satellite.
Your satellite has captured an image of the planet’s surface. The photographed section can be
modeled as a grid. Each grid cell is either land, water, or covered by clouds. Clouds mean that the
surface could either be land or water, but we can’t tell.
An island is a set of connected land cells. Two cells are considered connected if they share an edge.
Given the image, determine the minimum number of islands that is consistent with the given
information.
Input
The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 50).
Each of the next n lines contains m characters, describing the satellite image. Land cells are
denoted by ‘L’, water cells are denoted by ‘W’, and cells covered by clouds are denoted by ‘C’.
Output
Print, on a single line, a single integer indicating the minimum number of islands that is consistent
with the given grid.


题目大意:有一张图其中有三种字符‘L’代表岛屿,‘W’代表水,‘C’代表云,求出这张图中岛屿的最小数量。也就是其中‘L’和‘W’都是确定的但是‘C’是可以变化的可以看做是‘W’或是‘L’。如样例一中我们吧所有的‘C’看做‘W’所以岛屿的数量为0,样例二中我们吧‘C’看做是‘L’这样图中左上角和右下角的‘L’就连城一个岛屿,所以最少岛屿数为1.
解题思路:
使用图的遍历(深度优先搜索、广度优先搜索)从图中的‘L’开始遍历,遍历其中能走到的‘C’和‘L’并标记已经走过,这样每遍历一个‘L’就能遍历该岛屿能与那些岛屿相连。
// Islands.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <bits/stdc++.h>
using namespace std;
struct nd
{
int x, y;
};
/*全局变量*/
string mp[55];
bool book[55][55];
int n, m;
/*自定义函数*/
void input();//输入地图
void bfs_search(int x,int y);//广度优先搜索
int count_land();//数最少多少岛屿
int main()
{
cin >> n >> m;
getchar();
input();//输入地图
int lands = count_land();
cout << lands << endl;
}
/*自定义函数*/
void input()//数据输入函数
{
for (int i = 0; i < n; i++)
{
getline(cin, mp[i]);
}
}
int next_x[4] = { 0,1,0,-1 }, next_y[4] = { 1,0,-1,0 };
void bfs_search(int x,int y)//广度优先搜索
{
book[x][y] = true;//标记该点已经走过
queue<nd>q;
nd cur, t;
t = { x,y };
q.push(t);//压入起始点
while (!q.empty())
{
//取出队列中的第一个元素
cur = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int tx = cur.x + next_x[i];
int ty = cur.y + next_y[i];
if (tx >= 0 && tx < n && ty >= 0 && ty < m
&& !book[tx][ty] && mp[tx][ty] != 'W')
//如果该点在地图中
//该点没有遍历过,且该点不是水
{
book[tx][ty] = true;
t = { tx,ty };
q.push(t);
}
}
}
}
int count_land()//数最少多少岛屿
{
//数据初始化
memset(book, false, sizeof(book));
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (mp[i][j] == 'L' && !book[i][j])
//如果该点是岛屿,并且没有遍历过,也就是不与之前遍历的岛屿相连
{
bfs_search(i,j);
cnt++;
}
}
}
return cnt;
}
本文介绍了一种算法,用于解决卫星图像中岛屿数量的最小可能计数问题。通过使用广度优先搜索,遍历地图上的每个岛屿,标记已访问过的土地和云覆盖区域,以确定最小岛屿数。
213

被折叠的 条评论
为什么被折叠?



