当前位置:网站首页>8.岛问题
8.岛问题
2022-07-16 16:40:00 【123_YQH】
岛问题
【题目】
一个矩阵中只有0和1两种值,每个位置都可以和自己的上、下、左、右四个位置相连,如果有一片1连在一起,这个部分叫做一个岛,求一个矩阵中有多少个岛?
【例子】
0 0 1 0 1 0
1 1 1 0 1 0
1 0 0 1 0 0
0 0 0 0 0 0
这个矩阵中有三个岛。
【进阶】
如何设计一个并行算法解决这个问题。
【思路】有一个infect函数,会把连城一片的1全变成2。深度优先遍历或者宽度优先遍历这个矩阵,遇到是1的元素则调用infect函数,最后调用了多少次infect函数就有多少个岛。
【代码】
int countIslands(vector<vector<int>> &matrix) {
if (matrix.empty()) {
return 0;
}
int m = matrix.size();
int n = matrix[0].size();
int res = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == 1) {
++res;
infect(matrix, i, j, m, n);
}
}
}
return res;
}
//infect函数,会把连城一片的1全变成2
void infect(vector<vector<int>> &vec, int i, int j, int m, int n) {
if (i < 0 || i >= m || j < 0 || j >= n || vec[i][j] != 1) {
return;
}
//i,j没越界,并且当前位置值都是1
vec[i][j] = 2;
infect(vec, i + 1, j, m, n);
infect(vec, i - 1, j, m, n);
infect(vec, i, j + 1, m, n);
infect(vec, i, j - 1, m, n);
}
边栏推荐
猜你喜欢

Orm déchiqueté à la main (générique + annotation + réflexion)

Dark horse programmer - software testing -14 stage 3- function testing -66-77 Zen introduction, product manager uses Zen, super administrator uses Zen, super administrator modifies security strategy,

电影知识图谱和基于模板的问答系统构建

Common functions of JMeter - parametric introduction

An Amway note taking tool -- Obsidian

HCIA summary

How to recover if the win11 mouse can't move? Win11 method of recovering from mouse immobility

Anaconda安装(非常详细)

Full marks for all! The Chinese team IMO won four consecutive titles, leading the second place South Korea by a big score

VIVADO 以太网接口(SGMII转GMII接口)
随机推荐
Day 4 training
[wechat applet] page configuration, network data request
Format output text in CAD
第四天训练
Optimisation des requêtes associées, optimisation des sept groupes de tri et analyse des requêtes d'interception
Dynamic parameter transfer of PHP for tag end attribute (ThinkPHP)
公司股权结构顶层设计方案(案例)
Ali side: what are the skills of SQL optimization?
低代码三部曲之起因
九、MySQL锁机制 十、复制
Tensorflow speed entry
The third part of building PSIM simulation model of buck circuit (simulation of digital difference equation)
1.4.2-SQL注入防御绕过-二次编码注入
Orm déchiqueté à la main (générique + annotation + réflexion)
Zordle:基于ZKP的Wordle应用
中科大少年班录取名单公布:浙江狂揽三成名额,仅学军中学就有4人
Rizomuv exhibition UV usage notes
Equity distribution agreement (1)
Raspberry pie shutdown restart command
JMeter 21 day clock in day07