当前位置:网站首页>求岛屿最大面积--深度优先搜索(染色法)
求岛屿最大面积--深度优先搜索(染色法)
2022-07-23 08:00:00 【一只829】
问题描述:
给你一个大小为 m x n 的二进制矩阵 grid 。
岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
岛屿的面积是岛上值为 1 的单元格的数目。
计算并返回 grid 中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。

样例输入:
第一行:行列
5 4
1 1 1 0
0 0 0 1
1 1 1 0
0 1 0 0
0 1 1 1
样例输出:
7
基本思想:
深度优先搜索遍历所有大于0的结点。从第一块开始深度遍历大于1的结点赋值num,直到第一个结点回调结束 ,num++,继续下一个结点遍历,这样做到每一块的num都不一样。

最后计算最大数字的个数
完整代码:
//深度优先搜索 染色法
#include<iostream>
using namespace std;
int grid[100][100], book[100][100];
int n, m, num = 1;
void dfs(int i, int j, int num) {
int next[4][2] = {
{0,1},{1,0},{0,-1},{-1,0}
};
int k, tx, ty;
grid[i][j] = num;
cout << num << endl;
for (k = 0;k <= 3;k++) {
tx = i + next[k][0];
ty = j + next[k][1];
//边界条件
if (tx<1 || tx>n || ty<1 || ty>m)
continue;
if (grid[tx][ty] == 1 && book[tx][ty] == 0) {
book[tx][ty] = 1;
dfs(tx, ty, num);
}
}
return;
}
int main() {
int i, j;
int color[10] = { 0 };
cin >> n >> m;
for (i = 1;i <= n;i++)
for (j = 1;j <= m;j++)
cin >> grid[i][j];
cout << endl;
//对大于0的点进行染色
for (i = 1;i <= n;i++)
for (j = 1;j <= m;j++)
{
if (grid[i][j] == 1) {
book[i][j] = 1;
num++;
dfs(i, j, num);
}
}
for (i = 1;i <= n;i++) {
for (j = 1;j <= m;j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
for (i = 1;i <= n;i++)
for (j = 1;j <= m;j++) {
if (grid[i][j] > 1) {
color[grid[i][j]] ++;
}
}
i = 2;
while (color[i] != 0) {
i++;
}
cout << color[i - 1];
return 0;
}
边栏推荐
猜你喜欢
随机推荐
判断一个对象是否是空对象的处理办法
Day 12 notes
《Animal Farm》笔记
Life essays: annoying projects in 2022
rtx3080ti和3090差距 rtx3080ti和3090哪个性价比高
How many processors is Tianji 720 equivalent to Xiaolong? How about Tianji 720 equivalent to Xiaolong
赛扬n5095处理器怎么样 英特尔n5095核显相当于什么水平
Remember that a vulnhub target plane exercise successfully won the root permission
利用redis实现分布式锁(单个redis)
kafka消费报错coordinator unavailable.Rediscovery will be attempt redisCovery
js 实现通过身份证获取年龄
第四天笔记
小米12S Pro和小米12Pro天玑版区别 两者配置对比
OSPF comprehensive experiment
考研题库小程序中如何实现打开考研思维导图pdf
[understanding of opportunity-50]: Guiguzi - the twelfth Rune chapter - the art of being a good leader: keep your position, observe the four directions, cave in danger, talk widely, empty advice, set
What level is the notebook core i5 1135g7 equivalent to? How about i5 1135g7 performance
[wechat applet] case - local life
In depth analysis of common cross end technology stacks of app
Rtx3080 is equivalent to GTX. What kind of graphics card is rtx3080? What level is rtx3080








