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);
        }
    }
};
秃鹰搜索优化算法(BES)详解:从自然捕食到全局优化 秃鹰搜索优化算法(Bald Eagle Search Optimization Algorithm,BES)是由马来西亚学者Alsattar等人于2020年提出的一种新型元启发式优化算法。该算法灵感来源于秃鹰在自然界中高超的捕食行为,特别是其独特的狩猎策略和卓越的视觉搜索能力,模拟了秃鹰捕食鲑鱼等猎物的完整过程。 阅读详情

相关推荐

IGBT基础知识

IGBT

u010783226的专栏 1万+

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 499

Nvidia AGX Xavier刷机指北

因为工作的关系,要在AGX上安装CUDA。nvidia官网上没找到适合AGX版本的CUDA,只能走刷机的路子。刷机过程中,也遇到一些坑,做个记录。 需要有一台ubuntu系统的电脑作为主机Host。我的主机系统为Ubuntu18.04 整个刷机过程为: 在Host上安装sdkmanager,整个刷机过程主要通过sdkmanager来操作。 在Host自动下载一些系统组件,各种deb包 Host上制作OS系统镜像,烧录到AGX中 Host上之前下载好的deb包,安装到AGX中。 完结,撒花 ...

sinat_38685124的博客 6303

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

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

weixin_44015873的博客 340

CTFshow-pwn入门-前置基础pwn32-pwn34

CTFshow-pwn入门-前置基础pwn32-pwn34

你们de4月天的博客 1144

华为 S2600T 存储 3 种网络端口(H4/H5/串口)用途解析与故障恢复实战

本文深度解析华为S2600T存储设备的三种关键网络端口(H4/H5/串口)的功能用途与故障恢复方法。通过详细的配置指南和实战案例,帮助管理员掌握管理接口(H4)的日常运维、维护接口(H5)的高级应用以及串口的应急操作,提升存储设备的可靠性和维护效率。

weixin_30899023的博客 347

孤岛数量

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

四参数与七参数坐标转换含义及区别

一.前言 不同坐标系,其椭球体的长半径,短半径和扁率是不同的。比如我们常用的四种坐标系北京54、西安80、WGS84、CGCS2000所对应的椭球体,它们的椭球体参数就各不相同。而不同空间直角坐标系之间的转换一般通过七参数或者四参数来实现坐标转换。 二.四参数转换 两个不同的二维平面直角坐标系之间转换通常使用四参数模型,四参数适合小范围测区的空间坐标转换,相对于七参数转换的优势在于只需要2个公共已知点就能进行转换,操作简单。 在该模型中有四个未知参数,即: (1)两个坐标平...

尘海折柳的博客 1万+

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

AI原生SaaS应用的自动化运维体系构建

随着ChatGPT掀起的AI原生应用浪潮,越来越多SaaS(软件即服务)产品开始以"AI优先"的方式设计——从用户交互到核心功能,都深度依赖机器学习模型(如推荐算法、智能客服)、实时数据流(如用户行为分析)和弹性算力(如大模型推理)。这类应用的运维需求与传统SaaS完全不同:传统运维像"修水管",哪里漏了补哪里;AI原生运维则像"照顾会成长的宠物",需要实时感知模型状态、数据变化和流量波动,主动调整资源。

AI天才研究院 1093

SAP_FICO模块-资产减值功能对折旧和残值的影响

SAP_FICO模块-资产减值操作对资产历史折旧以及后续折旧的影响,包括减值操作的配置前提

风沙的博客 2828

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

【微服务】SpringBoot 整合 FastExcel 实现导入导出操作详解

SpringBoot 整合 FastExcel 实现导入导出操作详解

congge 4251

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

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

计算机控制技术及应用

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

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 918

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

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

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

ivyusing的博客 843

ssm框架搭建

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

Number of Islands问题及解法

200. Number of Islands LeetCode

刘天的博客 950

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

小人物的草稿本 855

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

【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万+

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的专栏 511

Python宽搜(BFS)和深搜(DFS)

目录BFSBFS是什么BPS工作过程和原理BFS应用场景python实现BFS(树和图)python实现BFS图python实现图的最短路径python实现BFS树DFSDFS是什么DFS工作过程和原理DFS应用场景python实现DFSpython实现DFS图python实现DFS树何时使用深搜和广搜python实现树前中后序遍历前序遍历中序遍历后序遍历参考资料 BFS BFS是什么 BFS称为宽度优先搜索也叫做广度优先搜索,其别名又叫BFS,属于一种盲目搜寻法。 Dijkstra单源最短路径算法和Pri

gy的博客 6092

Breadth First Search in Python (宽度/广度优先搜索)

宽搜/广搜简称BFS,Dijkstra单源最短路径算法和Prim最小生成树算法均使用广搜的思想,从一点出发向外辐射直至遍历所有结点。本文主要总结在图和树(特殊的图)上的广搜。2)parent字典用于记录某结点的父结点,方便路径回溯;flag为一个集合,用于标记已经遍历过的结点(该图为无向图);s为起始结点,v为终止结点。1)此处手动输入了示例1,若实际图过大或复杂可以设置相应类。图的广度优先搜索(图源为AI AX AT)图的广度优先搜索(图源为AI AX AT)1)树的广度优先搜索本质上即为树的层次遍历。

m0_45175452的博客 497

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

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

2201_75554489的博客 2712

奇怪的电梯

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

菲菲家的吴先森 1271

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

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址