代码随想录Day 51|题目:99.岛屿数量、100.岛屿的最大面积

提示:DDU,供自己复习使用。欢迎大家前来讨论~

文章目录

    • 题目一:99. 岛屿数量
    • 思路
      • 深度优先搜索DFS
      • 广度优先搜索BFS
    • 题目二:100. 岛屿的最大面积
      • DFS
      • BFS
    • 总结

题目一:99. 岛屿数量

99. 岛屿数量 (kamacoder.com)

思路

注意题目中每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

也就是说对角线上是不算的, 例如示例二,是三个岛屿,如图:

图一

这道题题目是 DFS,BFS,并查集,基础题目。

本题思路,是用遇到一个没有遍历过的节点陆地,计数器就加一,然后把该节点陆地所能遍历到的陆地都标记上。

在遇到标记过的陆地节点和海洋节点的时候直接跳过。 这样计数器就是最终岛屿的数量。

那么如何把节点陆地所能遍历到的陆地都标记上呢,就可以使用 DFS,BFS或者并查集。

深度优先搜索DFS

思路:

  1. 初始化:创建一个变量result来存储岛屿的数量,初始值为0。
  2. 检查边界条件:如果网格为空或没有行,直接返回0。
  3. 双层循环:使用两个嵌套循环遍历网格的每一行和每一列。
  4. 找到陆地:在内层循环中,检查每个单元格是否为’1’。如果是,增加result的值,并对该单元格进行DFS。
  5. DFS函数:DFS函数将遍历当前单元格的所有四个方向(上、下、左、右),如果相邻单元格是陆地(值为’1’)并且没有越界,则递归调用DFS,并标记该单元格为已访问。
  6. 结束条件:当所有单元格都被检查过,返回result作为最终的岛屿数量。

注意:

  • 递归:DFS是递归实现的,每次递归调用都会检查一个方向的相邻单元格。
  • 边界检查:在DFS中,每次移动前都要检查是否会越界,以避免访问数组之外的内存。
  • 标记已访问:在DFS中,一旦访问了一个陆地单元格,就将其标记为已访问(通常是将’1’改为’0’),以避免重复计数。

下面给出两种版本的代码:

  1. 版本一的写法
    • 在调用DFS之前,先对节点进行合法性检查。
    • 只有当节点是合法的(即在网格范围内且是陆地)时,才调用DFS函数。
    • 这样做可以减少不必要的递归调用,从而提高效率。
  2. 版本二的写法
    • 不管节点是否合法,都先调用DFS函数。
    • 在DFS函数内部,通过终止条件来判断节点是否合法。
    • 如果节点不合法(例如,是水或者越界),则直接返回,不进行进一步的递归。
    • 这种写法可能在理解上更直观,因为所有的递归逻辑都封装在DFS函数内部。

两种写法的主要区别在于何时进行合法性检查。版本一在调用DFS之前进行检查,而版本二在DFS函数内部进行检查。理论上,版本一的效率可能更高,因为它避免了对不合法节点的递归调用。然而,从代码的可读性角度来看,版本二可能更清晰,因为它将所有的递归逻辑集中在一起。

完整C++代码如下:

// 版本一 
#include <iostream>
#include <vector>
using namespace std;int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {for (int i = 0; i < 4; i++) {int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过if (!visited[nextx][nexty] && grid[nextx][nexty] == 1) { // 没有访问过的 同时 是陆地的visited[nextx][nexty] = true;dfs(grid, visited, nextx, nexty);}}
}int main() {int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {cin >> grid[i][j];}}vector<vector<bool>> visited(n, vector<bool>(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] == 1) {visited[i][j] = true;result++; // 遇到没访问过的陆地,+1dfs(grid, visited, i, j); // 将与其链接的陆地都标记上 true}}}cout << result << endl;
}

为什么 以上代码中的dfs函数,没有终止条件呢? 感觉递归没有终止很危险。

其实终止条件 就写在了 调用dfs的地方,如果遇到不合法的方向,直接不会去调用dfs。

当然也可以这么写:

// 版本二
#include <iostream>
#include <vector>
using namespace std;
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {if (visited[x][y] || grid[x][y] == 0) return; // 终止条件:访问过的节点 或者 遇到海水visited[x][y] = true; // 标记访问过for (int i = 0; i < 4; i++) {int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过dfs(grid, visited, nextx, nexty);}
}int main() {int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {cin >> grid[i][j];}}vector<vector<bool>> visited(n, vector<bool>(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] == 1) {result++; // 遇到没访问过的陆地,+1dfs(grid, visited, i, j); // 将与其链接的陆地都标记上 true}}}cout << result << endl;
}

最后是另一个更清晰简单的思路的C++代码:

#include <vector>
using namespace std;class Solution {
public:int numIslands(vector<vector<char>>& grid) {if (grid.empty() || grid[0].empty()) {return 0;}int result = 0;int row = grid.size();int col = grid[0].size();for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {if (grid[i][j] == '1') {result++;dfs(grid, i, j, row, col);}}}return result;}private:void dfs(vector<vector<char>>& grid, int x, int y, int row, int col) {if (x < 0 || y < 0 || x >= row || y >= col || grid[x][y] == '0') {return;}grid[x][y] = '0'; // 标记为已访问dfs(grid, x - 1, y, row, col); // 向上dfs(grid, x + 1, y, row, col); // 向下dfs(grid, x, y - 1, row, col); // 向左dfs(grid, x, y + 1, row, col); // 向右}
};

广度优先搜索BFS

BFS和队列数据结构是相辅相成的

本题完整广搜代码:

#include <iostream>
#include <vector>
#include <queue>
using namespace std;int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向
void bfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {queue<pair<int, int>> que;que.push({x, y});visited[x][y] = true; // 只要加入队列,立刻标记while(!que.empty()) {pair<int ,int> cur = que.front(); que.pop();int curx = cur.first;int cury = cur.second;for (int i = 0; i < 4; i++) {int nextx = curx + dir[i][0];int nexty = cury + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过if (!visited[nextx][nexty] && grid[nextx][nexty] == 1) {que.push({nextx, nexty});visited[nextx][nexty] = true; // 只要加入队列立刻标记}}}
}int main() {int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {cin >> grid[i][j];}}vector<vector<bool>> visited(n, vector<bool>(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] == 1) {result++; // 遇到没访问过的陆地,+1bfs(grid, visited, i, j); // 将与其链接的陆地都标记上 true}}}cout << result << endl;
}

另一种解法:

#include <vector>
#include <queue>
#include <iostream>
using namespace std;class Solution {
public:int numIslands(vector<vector<char>>& grid) {if (grid.empty() || grid[0].empty()) {return 0;}int result = 0;int row = grid.size();int col = grid[0].size();queue<pair<int, int>> q;for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {if (grid[i][j] == '1') {result++;q.push({i, j});grid[i][j] = '0';  // Mark as visitedwhile (!q.empty()) {auto cur = q.front();q.pop();int x = cur.first;int y = cur.second;// Check and mark neighborsif (x - 1 >= 0 && grid[x - 1][y] == '1') {q.push({x - 1, y});grid[x - 1][y] = '0';}if (y - 1 >= 0 && grid[x][y - 1] == '1') {q.push({x, y - 1});grid[x][y - 1] = '0';}if (x + 1 < row && grid[x + 1][y] == '1') {q.push({x + 1, y});grid[x + 1][y] = '0';}if (y + 1 < col && grid[x][y + 1] == '1') {q.push({x, y + 1});grid[x][y + 1] = '0';}}}}}return result;}
};int main() {Solution solution;vector<vector<char>> grid = {{'1', '1', '0', '0', '0'},{'0', '1', '1', '0', '0'},{'0', '0', '0', '1', '1'},{'1', '0', '0', '0', '1'},{'0', '1', '1', '0', '0'}};cout << "Number of islands: " << solution.numIslands(grid) << endl;return 0;
}

题目二:100. 岛屿的最大面积

100. 岛屿的最大面积 (kamacoder.com)

DFS

在编写DFS(深度优先搜索)函数时,存在两种常见写法:一种是在DFS函数外部进行合法性检查后再调用DFS,另一种是在DFS函数内部通过终止条件进行判断。

写法一,dfs只处理下一个节点,即在主函数遇到岛屿就计数为1,dfs处理接下来的相邻陆地

// 版本一
#include <iostream>
#include <vector>
using namespace std;
int count;
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向
void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {for (int i = 0; i < 4; i++) {int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过if (!visited[nextx][nexty] && grid[nextx][nexty] == 1) { // 没有访问过的 同时 是陆地的visited[nextx][nexty] = true;count++;dfs(grid, visited, nextx, nexty);}}
}int main() {int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {cin >> grid[i][j];}}vector<vector<bool>> visited(n, vector<bool>(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] == 1) {count = 1;  // 因为dfs处理下一个节点,所以这里遇到陆地了就先计数,dfs处理接下来的相邻陆地visited[i][j] = true;dfs(grid, visited, i, j); // 将与其链接的陆地都标记上 trueresult = max(result, count);}}}cout << result << endl;}

写法二,dfs处理当前节点,即在主函数遇到岛屿就计数为0,dfs处理接下来的全部陆地

dfs

// 版本二
#include <iostream>
#include <vector>
using namespace std;int count;
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向
void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {if (visited[x][y] || grid[x][y] == 0) return; // 终止条件:访问过的节点 或者 遇到海水visited[x][y] = true; // 标记访问过count++;for (int i = 0; i < 4; i++) {int nextx = x + dir[i][0];int nexty = y + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 越界了,直接跳过dfs(grid, visited, nextx, nexty);}
}int main() {int n, m;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {cin >> grid[i][j];}}vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] == 1) {count = 0; // 因为dfs处理当前节点,所以遇到陆地计数为0,进dfs之后在开始从1计数dfs(grid, visited, i, j); // 将与其链接的陆地都标记上 trueresult = max(result, count);}}}cout << result << endl;
}

两种DFS写法的差异主要在于何时进行岛屿计数:一种是在主函数中遇到新陆地即计数,另一种是将计数完全放在DFS函数内部处理。这种差异导致了不同的代码风格和逻辑结构,也是造成DFS实现方式多样性的根本原因。

BFS

本题BFS代码如下:

class Solution {
private:int count;int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 四个方向void bfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {queue<int> que;que.push(x);que.push(y);visited[x][y] = true; // 加入队列就意味节点是陆地可到达的点count++;while(!que.empty()) {int xx = que.front();que.pop();int yy = que.front();que.pop();for (int i = 0 ;i < 4; i++) {int nextx = xx + dir[i][0];int nexty = yy + dir[i][1];if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue; // 越界if (!visited[nextx][nexty] && grid[nextx][nexty] == 1) { // 节点没有被访问过且是陆地visited[nextx][nexty] = true;count++;que.push(nextx);que.push(nexty);}}}}public:int maxAreaOfIsland(vector<vector<int>>& grid) {int n = grid.size(), m = grid[0].size();vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));int result = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (!visited[i][j] && grid[i][j] == 1) {count = 0;bfs(grid, visited, i, j); // 将与其链接的陆地都标记上 trueresult = max(result, count);}}}return result;}
};

总结

BFS、DFS、并查集解决岛屿问题

  1. 算法选择
    • BFS:适用于层级遍历,可以找到最短路径,适合于岛屿问题因为它可以逐层扩展,直到所有相连的陆地都被访问。
    • DFS:适用于深度遍历,可以探索所有可能的路径,适合于岛屿问题因为它可以深入探索每个岛屿直到尽头。
    • 并查集:适用于处理动态连通性问题,通过合并操作来识别和跟踪连通的组件,适合于岛屿问题因为它可以快速判断和合并相连的陆地。
  2. 实现方式
    • BFS:使用队列存储待访问的节点,逐层访问,每访问一个陆地节点,就将其所有未访问的相邻陆地节点加入队列。
    • DFS:使用递归或栈存储待访问的节点,深入访问,每访问一个陆地节点,就递归地访问其所有未访问的相邻陆地节点。
    • 并查集:使用集合数据结构,每个陆地节点初始时属于自己的集合,当访问到相邻陆地时,通过并查集的合并操作将它们归为同一集合。
  3. 效率和适用性
    • BFS:在某些情况下可能比DFS更高效,因为它按层次访问,可以更快地找到所有相邻的陆地,但空间复杂度较高。
    • DFS:在递归深度不大的情况下非常高效,但可能会导致栈溢出,特别是在深度很大的网格中。
    • 并查集:在处理大规模数据时通常更高效,因为它减少了重复访问和递归调用,但需要额外的空间来维护集合信息。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1541668.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

Java高级Day48-JDBC-API和JDBC-Utils

127.JDBC API 128.JDBC-Utils public class JDBCUtils {//这是一个工具类&#xff0c;完成mysql的连接和关闭资源//顶柜相关的属性&#xff08;4个&#xff09;&#xff0c;因为只需要一份&#xff0c;因此做成staticprivate static String user;//用户名private static Stri…

Vision Transformer (ViT)、Swin Transformer 和 Focal Transformer

1. Vision Transformer (ViT) Vision Transformer详解-CSDN博客https://blog.csdn.net/qq_37541097/article/details/118242600?ops_request_misc%257B%2522request%255Fid%2522%253A%2522F8BBAFBF-A4A1-4D38-9C0F-9A43B56AF6DB%2522%252C%2522scm%2522%253A%252220140713.13…

如何把python(.py或.ipynb)文件打包成可运行的.exe文件?

将 Python 程序打包成可执行的 .exe 文件&#xff0c;通常使用工具如 PyInstaller。这是一个常用的 Python 打包工具&#xff0c;可以将 Python 程序打包成独立的可执行文件&#xff0c;即使没有安装 Python 也能运行。 步骤&#xff1a; 1. 安装 PyInstaller 使用 conda 安…

如何在Linux Centos7系统中挂载群晖共享文件夹

前景&#xff1a;企业信息化各种系统需要上传很多的图片或者是文件&#xff0c;文件如何在群晖中显示&#xff0c;当文件或者图片上传到linux指定文件夹内&#xff0c;而文件夹又与群晖共享文件夹进行挂载&#xff0c;就能保证上传的文件或者图片出现在群晖并在群晖里进行管理。…

Java之继承1

1. 继承 1.1 为什么要继承 在Java中我们定义猫类和狗类&#xff0c;如下 public class Cat {public String name;public int age;public String color;public void eat(){System.out.println(name "正在吃饭");}public void sleep(){System.out.println(name &qu…

网页聊天——测试报告——Selenium自动化测试

一&#xff0c;项目概括 1.1 项目名称 网页聊天 1.2 测试时间 2024.9 1.3 编写目的 对编写的网页聊天项目进行软件测试活动&#xff0c;揭示潜在问题&#xff0c;总结测试经验 二&#xff0c;测试计划 2.1 测试环境与配置 服务器&#xff1a;云服务器 ubuntu_22 PC机&am…

国庆电影扎堆来袭,AI智能体帮你推荐必看佳片!(附制作教程)

大家好&#xff0c;我是凡人。 今天看到新闻&#xff0c;发现国庆有10部影片要扎堆儿上映&#xff0c;对于选择困难症的我属实有点难选&#xff0c;同时也想避开一些坑省的浪费金钱和时间。 本着不知道就问AI的习惯&#xff0c;想问问大模型怎么看&#xff0c;但做了简单的交…

Go语言基础学习02-命令源码文件;库源码文件;类型推断;变量重声明

命令源码文件 GOPATH指向的一个或者多个工作区&#xff0c;每个工作区都会有以代码包为基本组织形式的源码文件。 Go语言中源码文件可以分为三类&#xff1a;命令源码文件、库源码文件、测试源码文件。 命令源码文件&#xff1a; 命令源码文件是程序的运行入口&#xff0c;是每…

descrTable常用方法

descrTable 为 R 包 compareGroups 的重要函数&#xff0c;有关该函数以及 compareGroups 包的详细内容见&#xff1a;R包compareGroups详细用法 加载包和数据 library(compareGroups)# 加载 REGICOR 数据&#xff08;横断面&#xff0c;从不同年份纳入&#xff0c;每个变量有…

十五、差分输入运算放大电路

差分输入运算放大电路 1、差分输入运算放大电路的特点、用途&#xff0c; 2、输出信号电压与输入信号电压的关系。

Python | Leetcode Python题解之第420题强密码检验器

题目&#xff1a; 题解&#xff1a; class Solution:def strongPasswordChecker(self, password: str) -> int:n len(password)has_lower has_upper has_digit Falsefor ch in password:if ch.islower():has_lower Trueelif ch.isupper():has_upper Trueelif ch.isdi…

YOLOv10 简介

YOLOv10&#xff0c;由清华大学的研究人员基于 Ultralytics Python 包构建&#xff0c;引入了一种全新的实时目标检测方法&#xff0c;该方法解决了以往 YOLO 版本中后处理和模型架构方面的不足。通过消除非极大值抑制&#xff08;NMS&#xff09;并优化各种模型组件&#xff0…

Linux文件IO(五)-三种进程退出方法及空洞文件

1.三种进程退出方法 return 当程序在执行某个函数出错的时候&#xff0c;如果此函数执行失败会导致后面的步骤不能在进行下去时&#xff0c;应该在出错时终止程序运行&#xff0c;不应该让程序继续运行下去&#xff0c;那么如何退出程序、终止程序运行呢&#xff1f;有过编程…

数据结构:内部排序

文章目录 1. 前言1.1 什么是排序&#xff1f;1.2 排序的稳定性1.3 排序的分类和比较 2. 常见的排序算法3. 实现常见的排序算法3.1 直接插入排序3.2 希尔排序3.3 直接选择排序3.4 堆排序3.5 冒泡排序3.6 快速排序3.6.1 hoare思想3.6.2 挖坑法3.6.3 lomuto前后指针法3.6.4 非递归…

Mobile net V系列详解 理论+实战(3)

Mobilenet 系列 论文精讲部分0.摘要1. 引文2. 引文3. 基础概念的讨论3.1 深度可分离卷积3.2 线性瓶颈3.3 个人理解 4. 模型架构细节5. 实验细节6. 实验讨论7. 总结 论文精讲部分 鉴于上一小节中采用的代码是V2的模型&#xff0c;因此本章节现对V2模型论文讲解&#xff0c;便于…

GPT-4o在matlab编程中性能较好,与智谱清言相比

边标签由矩阵给出 s [1 2 3 3 3 3 4 5 6 7 8 9 9 9 10]; t [7 6 1 5 6 8 2 4 4 3 7 1 6 8 2]; G graph(s,t); plot(G) ------------------- GPT-4o给出的代码可用&#xff0c; clc;clear; % 定义边的起点和终点 s [1 2 3 3 3 3 4 5 6 7 8 9 9 9 10]; t [7 6 1 5 6 8 2 …

【数据结构-二维差分】力扣2536. 子矩阵元素加 1

给你一个正整数 n &#xff0c;表示最初有一个 n x n 、下标从 0 开始的整数矩阵 mat &#xff0c;矩阵中填满了 0 。 另给你一个二维整数数组 query 。针对每个查询 query[i] [row1i, col1i, row2i, col2i] &#xff0c;请你执行下述操作&#xff1a; 找出 左上角 为 (row1…

计算机毕业设计 社区医疗服务系统的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

使用Diskgenius系统迁移

使用Diskgenius系统迁移 1、使用系统迁移2、注意点3、新备份的系统盘装在电脑上可能出现盘符错乱导致开机不进入桌面情况 1、使用系统迁移 参考视频&#xff1a; DiskGenius无损系统迁移&#xff0c;换硬盘无需重装系统和软件 2、注意点 1&#xff09;新的硬盘里面的所有资料…

数据结构_1.1、数据结构的基本概念

1、基本概念 数据&#xff1a;是信息的载体&#xff0c;是描述客观事物属性的数、字符及所有能输入到计算机中并被计算机程序识别和处理的符号的集合。数据是计算机程序加工的原料。 数据元素&#xff1a;数据元素是数据的基本单位&#xff0c;通常作为一个整体进行考虑和处理…