LintCode 433, LeetCode 200: Number of Islands (经典BFS/DFS/Union-Find)

Linux面试基本200道题 Linux面试基本100道题 1.cron 后台常驻程序 (daemon) 用于: A. 负责文件在网络中的共享 B. 管理打印子系统 C. 跟踪管理系统信息和错误 D. 管理系统日常任务的调度 在大多数Linux发行版本中,以下哪个属于块设备 (block devices) ? A. 串行口 B. 硬盘 C. 虚拟终端 D. 打印机 下面哪个Linux命令可以一次显示一页内容? A. pause B. cat C. more D. grep 怎样了解您在当前目录下还有多大空间? A. Use 阅读详情
  1. Number of Islands

Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Find the number of islands.

Example
Example 1:

Input:
[
[1,1,0,0,0],
[0,1,0,0,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,0,0,1]
]
Output:
3
Example 2:

Input:
[
[1,1]
]
Output:
1

这题是经典宽搜(BFS)题。有3种解法,BFS,并查集和DFS。
解法1: BFS
注意:
1)遍历每个节点,若为1,则调用bfs。
2)bfs的主要作用就是从该节点向4个方向扩展,把相连的节点设为false。这里要注意的是,把相连的节点设为false后,该节点还是要进queue,不然该方向的宽搜就断了。
3)可以用两个数组dirX和dirY和一个for循环(0…3)来搜索4个方向。
4)每次调用bfs的时候,该节点本身要设为false,这样就不会重复查找了。
5) 每次调用bfs的时候,num_islands只加1,因为所有相连的节点加起来只能算一个。
6) queue里面放coordinate的值而不是指针。
7) queue的操作是
queue.pop() //不返回值
queue.push(node) //从back push
queue.front() //返回queue最front的元素
注意网上有的地方用queue.pop_front()和queue.push_back()。这两个函数我试了不支持,可能是C++版本不一样的原因?

代码如下:

    struct coordinate {
        int x;
        int y;
        coordinate (int x, int y) {
            this->x=x;
            this->y=y;
        }
    };

    int numIslands(vector<vector<bool>> &grid) {
        int num_row=grid.size();
        if (num_row==0) return 0;
        
        int num_col=grid[0].size();
        int num_islands=0;
        
        for (int i=0; i<num_row; ++i) {
            for (int j=0; j<num_col; ++j) {
                if (grid[i][j]) {
                    bfs(grid, i, j);
                    num_islands++;
                }
            }        
        }
        
        return num_islands;
    }

    void bfs(vector<vector<bool>> &grid, int x, int y) {
        //north, east, west, south
        vector<int> dirX = {0,1,-1,0};
        vector<int> dirY = {1,0,0,-1};    
        queue<coordinate> q;
        
        q.push(coordinate(x,y)); //also we can use coordinate temp = coordinate(x, y); and q.push(temp);
        grid[x][y]=false;
        
        while(!q.empty()) {
            coordinate node = q.front();
            q.pop();
            for (int i=0; i<4; i++) {
                coordinate neighbour = coordinate(node.x+dirX[i], node.y+dirY[i]);
            
                if (!(neighbour.x>=0 && neighbour.x<grid.size() && neighbour.y>=0 && neighbour.y<grid[0].size()))
                    continue;
                
                if (grid[neighbour.x][neighbour.y]) {
                    grid[neighbour.x][neighbour.y]=false;
                    q.push(neighbour);
                }   
            }
        }
    } 

二刷:

class Solution {
public:
    /**
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
    int numIslands(vector<vector<bool>> &grid) {
        int rowSize = grid.size();
        if (rowSize == 0) return 0;
        int colSize = grid[0].size();
        if (colSize == 0) return 0;

        int res = 0;
        int dx[4] = {0, 0, 1, -1};
        int dy[4] = {1, -1, 0, 0};

        queue<pair<int, int>> q;
        vector<vector<bool>> visited(rowSize, vector<bool>(colSize, false));
        
        for (int i = 0; i < rowSize; i++) {
            for (int j = 0; j < colSize; j++) {
                
                if (!visited[i][j] && grid[i][j] == 1) {
                    res++;
                    q.push({i, j});
                } else {
                    continue;
                }
                while (!q.empty()) {
                   auto frontNode = q.front();
                   q.pop();
                   
                   for (int k = 0; k < 4; k++) {
                       int newX = frontNode.first + dx[k];
                       int newY = frontNode.second + dy[k];
                       if (newX < 0 || newX >= rowSize ||
                           newY < 0 || newY >= colSize ||
                           visited[newX][newY] ||
                           grid[newX][newY] == 0
                           ) continue;
                       q.push({newX, newY});
                       visited[newX][newY] = true;
                   }
                }
            }
        }
       return res; 
    }
};

解法2:并查集 union-find。记得二维矩阵可以用i*col+j来转换成一维。

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int n_row = grid.size();
        int n_col = grid[0].size();
        father.resize(n_row * n_col + 1);
        //initialize, each node's father is itself
        for (int i = 0; i < n_row; i++) {
            for (int j = 0; j < n_col; j++) {
                int num = i * n_col + j;
                father[num] = num;
                if (grid[i][j] == '1') ans++;
            }
        }

       // vector<int> dx = {1, 0};
       // vector<int> dy = {0, 1};
        vector<int> dx = {0, 0, 1, -1};
        vector<int> dy = {1, -1, 0, 0};
        
        for (int i = 0; i < n_row; i++) {
            for (int j = 0; j < n_col; j++) {
                if (grid[i][j] == '1') {
                    for (int k = 0; k < 4; k++) {
                        int newX = i + dx[k];
                        int newY = j + dy[k];
                        if (newX >= 0 && newX < n_row && 
                            newY >= 0 && newY < n_col &&
                            grid[newX][newY] == '1') {
                            join(i * n_col + j, newX * n_col + newY);
                        }
                    }               
                }
            }
        }
        
        return ans;        
    }

private:
    vector<int> father;
    int ans = 0;
    
    int find(int x) {
       if (father[x] == x) {
           return x;
       }
        return father[x] = find(father[x]);
    }
    
    void join(int x, int y) {
        int fatherX = find(x);
        int fatherY = find(y);
        if (fatherX != fatherY) {
            father[fatherX] = fatherY;
            ans--;
        }
    }
};

改进:其实并查集的话,用右和下2个方向就可以了,因为执行到后面的时候,前面的都必然已经处理过了。
注意: DFS和BFS不能这么用! 看下面的例子

111
010
111

当DFS/BFS执行到num[2,1] 这个1(行列序号都从0开始)的时候,它是没有办法往左扩展的,所以num[2,0]这个1没法跟它连在一起。所以num[2,0]又会重新来一次BFS/DFS,而重新来一次的话,count就会加1,这样,就多算了一次。上图会被判为2个岛。
而并查集为什么可以呢?因为并查集算法是先把count初始化为所有的1的个数,然后,每次join的时候count–。这样,虽然num[2.1]不会主动连到num[2,0],但是轮到num[2,0]的时候,它会主动join num[2,1],这样count又会减1。答案正确。

int numIslands(vector<vector<char>>& grid) {
        int n_row = grid.size();
        int n_col = grid[0].size();
        father.resize(n_row * n_col + 1);
        //initialize, each node's father is itself
        for (int i = 0; i < n_row; i++) {
            for (int j = 0; j < n_col; j++) {
                int num = i * n_col + j;
                father[num] = num;
                if (grid[i][j] == '1') ans++;
            }
        }

        vector<int> dx = {1, 0};
        vector<int> dy = {0, 1};
        for (int i = 0; i < n_row; i++) {
            for (int j = 0; j < n_col; j++) {
                if (grid[i][j] == '1') {
                    for (int k = 0; k < 2; k++) {
                        int newX = i + dx[k];
                        int newY = j + dy[k];
                        if (newX >= 0 && newX < n_row && 
                            newY >= 0 && newY < n_col &&
                            grid[newX][newY] == '1') {
                            join(i * n_col + j, newX * n_col + newY);
                        }
                    }               
                }
            }
        }
        
        return ans;        
    }

解法3:深搜DFS。

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int n_row = grid.size();
        int n_col = grid[0].size();
        int count = 0;
        for (int i = 0; i < n_row; i++) {
            for (int j = 0; j < n_col; j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
private:
    void dfs(vector<vector<char>> &grid, int i, int j) {
        grid[i][j] = 0;
        int n_row = grid.size();
        int n_col = grid[0].size();
        int dx[4] = {0, 0, 1, -1};
        int dy[4] = {1, -1, 0, 0};
        for (int k = 0; k < 4; ++k) {
            int newX = i + dx[k];
            int newY = j + dy[k];
            if (newX >= 0 && 
                newX < n_row &&
                newY >= 0 &&
                newY < n_col &&
                grid[newX][newY] == '1') {
                dfs(grid, newX, newY);
            }
        }
    }
};

二刷:

class Solution {
public:
    /**
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
    int numIslands(vector<vector<bool>> &grid) {
        int rowSize = grid.size();
        if (rowSize == 0) return 0;
        int colSize = grid[0].size();
        if (colSize == 0) return 0;
        int res = 0;
        vector<vector<bool>> visited(rowSize, vector<bool>(colSize, false));
        
        for (int i = 0; i < rowSize; i++) {
            for (int j = 0; j < colSize; j++) {
                if (!visited[i][j] && grid[i][j] == 1) {
                    res++;
                    dfs(grid, i, j, visited);
                }
            }
        }
       return res; 
    }
private:
    void dfs(vector<vector<bool>>& grid, int row, int col, vector<vector<bool>>& visited) {
        int rowSize = grid.size();
        if (rowSize == 0) return;
        int colSize = grid[0].size();
        if (colSize == 0) return;
        
        int dx[4] = {0, 0, 1, -1};
        int dy[4] = {1, -1, 0, 0};

        for (int i = 0; i < 4; i++) {
            int newX = row + dx[i];
            int newY = col + dy[i];
            
            if (newX < 0 || newX >= rowSize ||
                newY < 0 || newY >= colSize ||
                visited[newX][newY] ||
                grid[newX][newY] == 0) {
                continue;
            }
            visited[newX][newY] = true;
            dfs(grid, newX, newY, visited);
        }
    }
};
Kindle使用USB数据线传书封面无法显示问题 不建议按这个解决封面问题,首先USB多次插拔麻烦,其次就是我起初按博主方法没啥问题,后面无论我怎么个顺序都出现了‘暂无图片’,我的建议是在亚马逊退出国内只能USB传书的情况下,下载一个calibre 和。飞行模式下用calibre传书到kindle ,然后用Fix Kindle Ebook Cover 修复一下,后面你要继续飞行模式还是连网随你便,两步完事。2,‘’发送到设备’的时候也最好选择 ‘发送特定格式至’ 选择具体的电子书格式,你的电子书是azw3就选azw3,是mobi就选mobi。 阅读详情

相关推荐

SRAM故障排查实战:如何用Nano Prober定位6T存储单元的异常点

本文详细介绍了在SRAM故障排查中,如何运用Nano Prober(纳米探针)技术精准定位6T存储单元的内部异常。面对传统方法难以发现的电性参数漂移(如晶体管阈值电压偏移)或微小物理缺陷,Nano Prober能直接对单个6T单元内的晶体管进行I-V特性测量,结合失效模式分析,有效解决读写错误等疑难问题,是芯片失效分析的关键工具。

v5w6x的博客 669

LeetCode 200:岛屿数量 Number of Islands

题目: 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded...

爱写Bug 497

ChromeOS安装教程

ChromeOS,是基于Linux内核研发的ChromiumOS开源系统的闭源系统,最大的特色就是内置了Chrome浏览器,早期主要以Web云端应用程序为主,后来逐渐引入了Android子系统和Linux子系统。本文主要简述摸索的家用笔记本安装ChromeOS安装方法,供各位玩机朋友参考。

weixin_45751495的博客 8128

BFS处理图的连通性问题 200 Number of Islands

这道题非常简单,因为和上一个题的解法基本相同(286 Walls and gates),只需要稍微变动一下就可以了,大概思路就是遍历整个图找到值为1的陆地,然后从这个点出发做BFS,将走过的地方设置成2(其实可以直接写成0的,我也不知道我当时怎么想的),BFS后继续找下一个值为1的陆地,继续上述步骤。每次找到新的陆地时计数器加1,最后返回计数器的值即可。 需要注意的是这道题的输入值是char,不要...

weixin_44015873的博客 340

DeepSeek API调用太复杂?OneAPI一站式聚合解决方案

本文介绍了OneAPI如何作为一站式聚合解决方案,简化DeepSeek API的调用流程。通过统一接口、智能路由和模型映射等核心功能,OneAPI大幅降低了多API适配的复杂性,提升开发效率。文章还提供了详细的部署指南和高阶使用技巧,帮助开发者快速实现API聚合管理。

weixin_27215337的博客 381

HC32 CAN通信

qqa

zhaopenglihui的博客 5438

孤岛数量

Find the Number of Islands 岛屿数量 问题描述 给定一个仅有0和1组成的矩阵,求不同的岛屿的个数。 其中0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。只考虑上下左右为相邻。同时假定矩阵之外的区域都为海。 测试样例 # Input: grid = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 1, 1, 0, 0]] # Output: 4 # 有四个

miaochengshi的博客 492

【行业解决方案篇十五】【DeepSeek物流优化:车辆路径规划算法】

写完这篇技术解析,突然想起那位多绕150公里的王师傅——现在他的车载平板会实时显示"路径健康度",当偏离最优路线超过5%就自动报警。从节约算法到深度强化学习,从三维装载到时序预测,这些技术最终化作每辆货车少烧的1升柴油,每个快递小哥早回家的1小时。最后说个浪漫的事:系统曾为某偏远山区规划出一条穿越枫叶林的配送路线,不仅节省23公里,还成了网红打卡路线。原来物流优化的尽头,不仅是冰冷的数学,还有人间烟火气的温度。

商务合作|问题讨论|交流学习 请联系作者微信,加微信请务必注明来意,博客主页有联系方式 295

Number of Islands C++

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 assum

悟 1319

080、多轴运动控制:插补器设计(螺旋线插补)

本文分享了螺旋线插补器设计的实战经验。针对五轴点胶机Z轴抖动问题,作者分析了螺旋线数学本质,提出基于归一化时间参数的速度规划方法,强调各轴严格同步的重要性。文章详细介绍了速度分解、加减速处理、嵌入式优化技巧(查表法、定点化),并总结了起点闭合、速度波动、数值处理等常见问题解决方案。最后给出5条实用建议:注重速度规划而非纯数学推导、预先仿真、保留调试接口、考虑机械谐振、防范编码器丢脉冲。通过优化插补周期、电子齿轮比和S形速度曲线,成功将设备良率从60%提升至95%。

m0_50546716的博客 89

WS2812和homeassistant握手

本文学习了WS2812和homeassistant握手,后期会分享更多有趣物联网的操作从而实现对外部世界进行感知,充分认识这个有机与无机的环境,科学地合理地进行创作和发挥效益,然后为人类社会发展贡献一点微薄之力。...

vor234的博客 816

算法题——Number of Islands(C++)BFS

由‘0’和‘1’组成的矩阵,上下左右视为相连,统计独立的'1's有多少块。 **知识储备:** BFS广度优先搜索,常常借助queue来实现。

ivyusing的博客 843

弱小目标检测跟踪算法研究(5) 基于顶帽变换(Top_hat)算法的红外弱小目标检测之背景抑制

基于顶帽变换(Top_hat)算法的红外弱小目标检测之背景抑制1. 前言2. 顶帽变换(Top_hat)算法3. Matlab仿真4. 小结 1. 前言 红外图像中的弱小目标,目标属性包涵“弱"和“小’’两个方面:“弱’’是指目标在红外波长上所表现出来的强度,具体反映到所拍摄的红外图像上,就是指目标的灰度值;而“小’’是指目标的尺寸大小,也就是前面所述的成像面积很小,反映到红外图像上就是指目标所占的像素数目很少。 SPIE国际光学工程学会(Societyof Photo一0ptical Instrument

sinat_34897952的博客 5295

200. Number of Islands(BFS)

https://leetcode.com/problems/number-of-islands/description/ 题目:求岛屿的数目,所有相连的1构成一个岛屿。 思路:BFS class Solution { public: int sum = 0; void BFS(vectorvectorchar>>& grid,int x,int y){ int

博客 573

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

leetcode -- Number of Islands -- DFS&BFS重点题

https://leetcode.com/problems/number-of-islands/要加上一个mask matrix 记录是否被访问过。思路见http://yucoding.blogspot.hk/2015/05/leetcode-questions-number-of-islands.html好好体会其与普通DFS的区别

xyqzki的专栏 1560

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Number of Islands问题及解法

200. Number of Islands LeetCode

刘天的博客 950

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

【LeetCode】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. Yo

跳出温水的青蛙 1万+

leetcode200. Number of Islands(DFS,BFS,UnionFound)

独立连通分量的个数: class Solution { private char[][] grid; public int numIslands(char[][] grid) { if(grid.length==0){ return 0; } this.grid=gri...

away_lit的博客 595

200:Number of Islands【DFS】【BFS】

题目链接:click~ /*题意:给出一个二维0和1的矩阵,判断有多少全是1的封闭区域*/ /** *思路:遍历矩阵,遇到1时,以该点为起始点,向四周做深度优先遍历,遇到 * 1是,标记为已访问的状态 * */ class Solution { private: int n,m; public: void DFS(vector> &grid, vector

no pains,no gains 913

200. Number of Islands(岛屿数量)——DFS深度优先搜索和BFS广度优先搜索

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...

mirana的专栏 508

Number of Islands BFS

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 horizontal

小人物的草稿本 854

【亲测免费】 全能搜题网页端源代码使用指南

全能搜题网页端源代码使用指南 项目介绍 全能搜题网页端 是一个永久免费且基于开源社区贡献的搜题系统。它旨在提供一个全面的搜题解决方案,允许用户搜索各种题目的解答,并支持开发者通过贡献代码或提供建议来共同优化与扩展这一平台。项目采用前后端分离的设计,前端部分由 React 和 TypeScript 强强联合,确保了良好的用户体验及系统可维护性。 项目快速启动 环境准备 确保你的开发环境中已安装 No...

gitblog_00358的博客 875

Linux 有哪些搜索方式?5分钟带你搞懂!

5分钟带你掌握 Linux 的三种搜索方式

2201_75554489的博客 2711

奇怪的电梯

Description 有一个奇怪的电梯,它可以停在任何一层楼,并且在每一层楼上有一个数字Xi 。 这个电梯只有两个按钮:UP 和 DOWN。 当你在第 i 层楼的时候,如果你按 UP ,那么你将上升 Xi 层楼(即是说你将到达第 i+Xi 层楼), 如果你按 DOWN,那么你将下降 Xi 层楼(即是说你将到达第 i-Xi 层楼)。 当然,你最多到达第 N 层楼,至少到达第 1 层楼。 例如,...

菲菲家的吴先森 1269

HDOJ1242 基础宽搜题

Rescue Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 32204    Accepted Submission(s): 11245 Problem Description Angel was caught

勇敢前进的ACMer 330

poj1011 深搜题代码解释

#include #include #include int n; int stick[100]; int total; int ns; int ok; int len;int used[100];int cmp(const void *a,const void *b) {    int a1 = *(int *)a;    int a2 = *(int *)b;    return

shuifa2008的专栏 739
上一篇: Binary Tree 非递归遍历模板小结(经典!)
下一篇: LintCode-127: Topological Soring 拓扑排序 (经典题)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值