200. Number of Islands+130. Surrounded Regions(并查集/DFS)

leetcode解题之200. Number of Islands Java版(岛屿的数量) leetcode解题之200. Number of Islands Java版(岛屿的数量) ,深度优先遍历 阅读详情

首先看200题:

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011

DFS:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty())
            return 0;
        m = grid.size();
        n = grid[0].size();
        int counter = 0;
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(grid[i][j] == '1'){
                    dfs_mark(grid, i, j);
                    ++counter;
                }
            }
        }
        return counter;
    }
    void dfs_mark(vector<vector<char>>& grid, int x, int y){
        if(x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != '1')
            return;
        grid[x][y] = '0';
        dfs_mark(grid, x-1, y);
        dfs_mark(grid, x+1, y);
        dfs_mark(grid, x, y-1);
        dfs_mark(grid, x, y+1);
    }
private:
    int m;
    int n;
};

并查集版本:

class Solution {
public:
    class uf_set {
    public:
        uf_set(const vector<vector<char>>& grid, int m, int n) 
            : father_(new int[m*n]), rnk_(new int[m*n]), counter_(0){
                fill(rnk_, rnk_+m*n, 0);
                for(int i=0; i<m; ++i){
                    for(int j=0; j<n; ++j){
                        if(grid[i][j] == '1'){
                            int id = i * n + j;
                            father_[id] = id;
                            ++counter_;
                        }
                    }
                }
        }
        ~uf_set(){
            delete []father_;
            delete []rnk_;
        }
    public:
        int find(int x){
            int root = x;
            while(root != father_[root])
                root = father_[root];

            while(x != father_[x]){
                int y = father_[x];
                father_[x] = root;
                x = y;
            }   
            return root;
        }
        void un(int x, int y){
            x = find(x), y = find(y);
            if(x == y) return ;
            if(rnk_[x] > rnk_[y]) father_[y] = x;
            else father_[x] = y, rnk_[y] += rnk_[x] == rnk_[y];
            --counter_;
        }
        int counter() const { return counter_; }

    private:
        int* father_;
        int* rnk_;
        int  counter_;
    };
public:
    vector<vector<char>> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty())
            return 0;
        int m = grid.size(), n = grid[0].size();
        uf_set us(grid, m, n);
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(grid[i][j] == '1'){
                    for(auto d: direction){
                        int x = i + d[0];
                        int y = j + d[1];
                        if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1'){
                            int id1 = i * n + j;
                            int id2 = x * n + y;
                            us.un(id1, id2);
                        }
                    }
                }
            }
        }
        int res = us.counter();
        return res;
    }
};

做上面这道题时,我强迫症发作,所以每个成员变量后面都加了后缀。后了一想,这样写项目很有用,写算法就是反而很鸡肋。于是我决定,以后写算法不在成员变量后面加后缀下划线了。

看130题。

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X
Subscribe to see which companies asked this question.

首先我直接用DFS:

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if(board.empty())
            return ;
        int m = board.size();
        int n = board[0].size();
        for(int i=0; i<m; ++i)
            if(board[i][0] == 'O') dfs_mark(board, m, n, i, 0);
        for(int j=1; j<n; ++j)
            if(board[0][j] == 'O') dfs_mark(board, m, n, 0, j);    
        for(int i=1; i<m; ++i)
            if(board[i][n-1] == 'O') dfs_mark(board, m, n, i, n-1);
        for(int j=1; j<n-1; ++j)
            if(board[m-1][j] == 'O') dfs_mark(board, m, n, m-1, j);
        for(int i=1; i<m-1; ++i){
            for(int j=1; j<n-1; ++j)
                if(board[i][j] != 'N') board[i][j] = 'X';
        }
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j)
                if(board[i][j] == 'N') board[i][j] = 'O';
        }
    }
    void dfs_mark(vector<vector<char>>& board, int m, int n, int x, int y){
        if(x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O') return;
        board[x][y] = 'N';
        dfs_mark(board, m, n, x-1, y);
        dfs_mark(board, m, n, x+1, y);
        dfs_mark(board, m, n, x, y-1);
        dfs_mark(board, m, n, x, y+1);
    }
};

然后超时了。但是我在网上搜这道题,在别的OJ上用这份代码通过了。所以leetcode要求还是蛮严格的。

然后是并查集版本:

class Solution {
public:
    vector<vector<char>> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    void solve(vector<vector<char>>& board) {
        if(board.empty())
            return;
        int m = board.size();
        int n = board[0].size();
        uf_set us(m*n+1);
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if((i == 0 || i == m-1 || j == 0 || j == n-1) && board[i][j] == 'O')
                    us.union_set(i*n+j, m*n);
                else if(board[i][j] == 'O'){
                    for(auto d : direction){
                        int x = i + d[0];
                        int y = j + d[1];
                        if(board[x][y] == 'O')
                            us.union_set(i*n+j, x*n+y);
                    }
                }
            }
        }

        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(us.find_set(i*n+j) != us.find_set(n*m))
                    board[i][j] = 'X';
            }
        }
    }
private:
    class uf_set {
    public:
        uf_set(int sz) : father(new int[sz]), rank(new int[sz]) {
            for(int i=0; i<sz; ++i){
                father[i] = i;
                rank[i] = 0;
            }
        }
        int find_set(int x){
            int root = x;
            while(root != father[root])
                root = father[root];

            while(x != father[x]){
                int y = father[x];
                father[x] = root;
                x = y;
            }
            return root;
        }
        void union_set(int x, int y){
            x = find_set(x), y = find_set(y);
            if(x == y) return;
            if(rank[x] > rank[y]) 
                father[y] = x;
            else 
                father[x] = y, rank[y] += rank[x] == rank[y];
        }
    private:
        int* father;
        int* rank;
    };
};

秒杀之。

vhr 微人事系统安装与部署教程(SpringBoot + Vue 项目实战) vhr(微人事)是一个开源的人力资源管理系统项目。系统采用前后端分离架构,主要技术栈包括:后端:MyBatis前端:VueElement UIAxios数据库:MySQL系统通常包含以下模块:员工管理部门管理职位管理薪资管理权限管理系统管理整体功能已经接近企业级后台系统。vhr(微人事)是一个非常经典的开源人力资源管理系统项目,基于SpringBoot + Vue 前后端分离架构。系统包含:员工管理部门管理权限管理薪资管理。 阅读详情

相关推荐

利用树莓派制作智能音箱

利用树莓派制作智能音箱

qq_61803022的博客 1779

200. Number of Islands (并查集)

200. Number of Islands Description Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizon...

Elo的博客 354

手把手教你为RK3588开发板适配RTL8211F网卡:设备树配置与PHY驱动匹配全流程

本文详细介绍了在RK3588开发板上适配RTL8211F千兆以太网PHY芯片的全流程,包括硬件原理图确认、设备树配置与PHY驱动匹配。通过实战案例和调试技巧,帮助开发者解决常见问题并优化网络性能,适用于嵌入式Linux开发中的Ethernet网络功能实现。

weixin_29184075的博客 527

LeetCode305. Number of Islands II - 彻底掌握并查集(Union Find)系列题5

​这道题是Leetcode200. Number of Islands的改进版,很显然可以用并查集(Union Find)来解答。唯一不同的就是陆地是随着positions数组动态增加的,每增加一块陆地就要统计当前岛屿的个数。由于我们再Union Find数据结构里维护了一个岛屿计数的变量,因此每增加一块新陆地,进行更新合并之后,我们就可以立刻得到岛屿的个数。

hgq522的博客 480

Linux中断子系统(二)—— 通用框架处理

1、数据结构分析 (1)中断描述符结构structirq_desc: 1)打开CONFIG_SPARSE_IRQ宏(中断编号不连续),中断描述符以radix- tree来组织,用户在初始化时进行动态分配,然后再插入radix-tree中; 2)关闭CONFIG_SPARSE_IRQ宏(中断编号连续),中断描述符以数组的 形式组织,并且已经分配好; 3)不管哪种形式,最终都可以通过linuxirq号来找到对应的中断描述符; (2)stru...

weixin_38428439的博客 4874

华为OD机试 新系统 双机位C卷 往年真题 机考题库(持续收录中)以及算法考点详解

每一题都有详细的答题思路、详细的代码注释、样例测试,发现新题目,随时更新,全天优快云在线答疑。

学Java,找哪吒 7万+

Leetcode200. Number of Islands - 彻底掌握并查集(Union Find)系列题1

这道的常规解法是用深度优先搜索(DFS)或宽度优先搜索(BFS)来解决。 其实这道题还可以用并查集(Union Find)算法来解决。我们知道并查集(Union Find)是用来解决连通问题,即处理集合的查找合并问题。而这道题里的岛的概念就是把连通的陆地合并成一个岛,相当于是矩阵里所有相连的‘1’合并成一个集合,最后集合个数就是所要求的岛的个数。

hgq522的博客 1081

【超分辨率(Super-Resolution)】关于【超分辨率重建】专栏的相关说明,包含专栏简介、专栏亮点、适配人群、相关说明、阅读顺序、超分理解、实现流程、研究方向、论文代码数据集汇总等

本专栏研究领域为【超分辨率重建】,涵盖图像超分、视频超分,实时超分,4K修复等方面。主要内容包括主流算法模型的论文精读、论文复现、毕业设计、涨点手段、调参技巧、论文写作、应用落地等方面。算法模型从SRCNN开始更新至今,一般是一篇论文精读对应一篇论文复现。论文精读详解理论,归化繁为简,归纳核心,积累词句,培养阅读论文和论文写作能力。论文复现依托Pytorch代码,实现完整的模型训练流程,总结调参方法,记录碰到的bug,论文插图可视化,培养读写代码能力、做实验的能力、以及应用落地能力。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 3万+

LeetCode 130 Surrounded Regions(并查集)

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X

nudt_oys的博客 1145

【系统架构设计师】模拟预测试卷十 - 案例分析(完整结构)

本文为系统架构设计师考试模拟试题及参考答案,包含五个专题:质量属性(必答)、信息系统架构设计、嵌入式系统架构设计、云原生架构设计、面向服务架构设计(SOA)。试题一聚焦非功能需求与质量属性映射,如性能、可修改性、一致性等;其余选答题分别涉及分层架构设计(如嵌入式实时控制)、云原生会话管理、服务化治理(如契约设计、熔断策略)等核心架构场景,涵盖战术应用、权衡分析及解决方案设计。参考答案提供关键要点,例如离线借还的冲突解决、服务编排与共享服务的区分、嵌入式硬实时保护的必要性等,适用于备考实战演练。

数据知道的博客 252

DOTS 性能基石:为什么传统 Unity 代码难以满足现代游戏需求?(DOTS 系列教程 · 第1篇)

本文探讨了Unity游戏开发中的性能优化问题,指出性能问题不应在最后才考虑,而应贯穿整个开发过程。文章分析了性能问题的三大表现(渲染开销、物理模拟、游戏逻辑),并解释了依赖硬件升级的不可行性。重点剖析了传统Unity代码性能低下的六大根源:垃圾回收卡顿、编译器优化不足、多核利用不足、数据结构和代码缓存不友好、过度抽象等问题。最后指出Unity项目中常见的反模式,如主线程垄断、内存碎片化等,为后续学习DOTS高性能架构解决方案奠定基础。

分享知识,拥抱变化 151

leetcode 200. Number of Islands-岛屿数量|并查集算法

原题链接:200. Number of Islands 【思路】 本题考查dfs和bfs的结合。由于题目没有限制不可改变原数组的结构,所以一旦遇到1,就将周边相邻的几个1置为2。遍历整个数组,遇到1的个数要求的解: public int numIslands(char[][] grid) { int islansNum = 0; for (int i

hdtopku 3258

161、车载环视系统的ISP多路同步架构——海思Hi3516DV300的4路鱼眼校正与拼接的帧同步误差控制

文章摘要: 针对海思Hi3516DV300车载环视系统四路鱼眼摄像头拼接画面动态撕裂问题,分析发现根本原因为帧同步误差(部分通道帧起始时间差1.2ms)。关键解决措施包括:1)通过VI通道主从同步模式(MASTER/SLAVE)结合软件补偿控制帧延迟;2)优化VPSS通道帧率锁定与丢帧策略确保拼接时序一致;3)严格校准鱼眼校正LUT参数与产线标定数据匹配;4)建议采用硬件同步信号(如sensor的FSIN引脚)降低软件同步压力。调试阶段需通过示波器直接测量sensor VSYNC信号,量产时需注意动态切换分

zzfmlxs的博客 138

LeetCode(130 & 200):被围绕的区域 & 岛屿数量 Surrounded Regions & Number of Islands(Java)

2019.8.11 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) 这两道题特别相似,所以就放到一起讨论了。 第一题是很明显是一个DFS,但是可以优化的地方在于,可以只沿边界的‘O’进行DFS单独标记。最后被标记的‘O’保留,其余未被标记的‘O’改为‘X’。 第二题同样可以用DFS一气呵成,不过还可以尝试使用BFS或者并查集(尽管并查集在本题上并不是个很好的方法)的做法来...

NJU_ChopinXBP的博客 337

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

<LeetCode OJ> 200 / 130 Number of Islands / Surrounded Regions

Total Accepted: 48411 Total Submissions: 171609 Difficulty: Medium Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and

EbowTang的练习场 1632

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

总结几道DFS的问题

为了感谢某人花了两天给我讲明白了DFS的问题… 我得赶紧把它们记下来… 问题来自leetcode,问题的集锦来自https://zhuanlan.zhihu.com/p/62884431 #695 这道题给了一个二维数组,0表示水,1表示陆地。问连在一起的1最多有几个。 a 是岛屿的数组 s 是状态数组 i,j代表位置 def dfs(a, s, i, j, ans)://在dfs中,我们首先要修...

qq_34471804的博客 523

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

leetcode思路总结反思(dfs篇)

leetcode思路总结反思(dfs篇) 130. Surrounded Regions (dfs蚕食法专题) 使用dfs,利用“蚕食法”,核心代码模板如下: for(int i=0;i<row;i++) { check(board,i,0,row,col); check(board,i,col-1,row,col); } ...

weixin_43886143的博客 280

leetcode|graph| 399. Evaluate Division 200. Number of Islands 130. Surrounded Regions

在boundary上或者和在boundary上格子相连的格子都不需要变成x。所以只需要思路同上地标记处所有不需要变的0就行(标记#之类的)。剩下的0就是要变成x的。dfs+memoization,需要用一个set记录某个点有没有作为起点使用过。用self,这样numIslands也可以access用dfs。所以这里grid[i][j]的改变会被带到外面。

amytheace的博客 324

LeetCode 200. Number of Islands&130. Surrounded Regions--DFS

两道题应该分别是我在蓝桥杯和南大夏令营遇到的原题,比较相似 题目链接 200. Number of Islands Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connect...

monkey_rose的博客 255

200. Number of Islands && 130. Surrounded Regions

200. Number of Islands Given a 2d grid map of'1's (land) and'0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally...

weixin_30535043的博客 84

[LeetCode] BFS解决的题目

一.130 Surrounded Regions(https://leetcode.com/problems/surrounded-regions/description/) 题目: 解法: 这道题的意思是将所有被X包围的O都变为X(边缘的不算),我们可以维护一个队列,先把四周的O的位置放进队列中,并把这个位置的值变为Y。然后每次从队列中拿出一个位置,把这个位置四周为O的位置...

aixian8156的博客 302

1.5 灵神题单总结_网格图_dfs

岛屿类题目全部基于。

凡物加倍磨治,皆能变化气质 204

(LeetCode 200)Number of Islands(并查集、DFS)

Q: Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may ass

SuperNova 3826

Leetcode 200 Number of Islands 并查集

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assu

无名山丘,崛起成峰 2703

(LeetCode 130)Surrounded Regions(并查集)

Q: Given a 2D board containing ‘X’ and ‘O’, capture all regions surrounded by ‘X’.A region is captured by flipping all ‘O’s into ‘X’s in that surrounded region.For example, X X X X X O O X X X O X

SuperNova 4025

LeetCode--200.Number of Islands(孤岛个数)Python

题目: 给定一个2维网格图,其中“1”(陆地)和“0”(水),计算岛屿的数量。岛屿被水包围,通过水平或垂直连接相邻的陆地形成。你可以假设网格的四边都被水包围着。例子如下图所示 解题思路: 从最左上角开始遍历这个网格图,当遍历到该点值为1的时候,将其更新为0,并以该点进行扩展,扩展方式为上下左右四个方向,扩展到的陆地(即值为1)将其值更新为0,直到不能扩展。再继续遍历下一个值为1点的,更新...

诚实的小小乐 4529
上一篇: 235.236:Lowest Common Ancestor of a Binary Search Tree/Tree(LCA问题)
下一篇: epoll内核实现分析
FreeeLinux
博客等级 码龄11年 421粉丝 356原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值