【LeetCode】200. Number of Islands 岛屿数量
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/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 horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
题目大意
有一片水域,四联通的算一个岛,求所有的岛的数目。
解题方法
DFS
这个题在《挑战程序设计竞赛》书的前面就讲了,我觉得还是挺经典的题目。可以直接套模板解决。
做法是,我们对每个有“1"的位置进行 DFS,把和它四联通的位置全部变成“0”,这样就能把一个点推广到一个岛。
所以,我们总的进行了 DFS 的次数,就是总过有多少个岛的数目。
注意理解dfs函数的意义:已知当前是1,把它周围相邻的所有1全部转成0.
代码如下:
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
res = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == "1":
self.dfs(grid, r, c)
res += 1
return res
def dfs(self, grid, i, j):
dirs = [[-1, 0], [0, 1], [0, -1], [1, 0]]
grid[i][j] = "0"
for dir in dirs:
nr, nc = i + dir[0], j + dir[1]
if nr >= 0 and nc >= 0 and nr < len(grid) and nc < len(grid[0]):
if grid[nr][nc] == "1":
self.dfs(grid, nr, nc)
C++版本的代码如下:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty())
return 0;
const int M = grid.size();
const int N = grid[0].size();
int res = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (grid[i][j] == '1') {
res ++;
dfs(grid, i, j);
}
}
}
return res;
}
void dfs(vector<vector<char>>& grid, int x, int y) {
grid[x][y] = '0';
const int M = grid.size();
const int N = grid[0].size();
for (auto& dir : dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx < 0 || nx >= M || ny < 0 || ny >= N || grid[nx][ny] == '0')
continue;
dfs(grid, nx, ny);
}
}
private:
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
};
BFS
这个题同样可以使用BFS解决。当遇到一个小岛的时候,做个BFS搜索,把它周围的小岛全部转成0即可。速度比DFS稍微慢了一点点。
Python 代码如下:
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid or not grid[0]: return 0
M, N = len(grid), len(grid[0])
que = collections.deque()
res = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for i in range(M):
for j in range(N):
if grid[i][j] == '1':
res += 1
grid[i][j] = '0'
que.append((i, j))
while que:
x, y = que.pop()
for d in directions:
nx, ny = x + d[0], y + d[1]
if 0 <= nx < M and 0 <= ny < N and grid[nx][ny] == '1':
grid[nx][ny] = '0'
que.append((nx, ny))
return res
在写 BFS 的时候可以把代码包装成一个函数,需要注意的是,由于BFS会把周围的1全部改成0,所以在出队列的时候,做一个判断,如果当前围着孩子已经被改了,那么就不用下面的搜索了。
C++代码如下:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.size() == 0 || grid[0].size() == 0) return 0;
const int M = grid.size(), N = grid[0].size();
int res = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (grid[i][j] == '1') {
++res;
bfs(grid, i, j);
}
}
}
return res;
}
// gird[x][y] = 1, delete it and its around.
void bfs(vector<vector<char>>& grid, int x, int y) {
const int M = grid.size(), N = grid[0].size();
queue<pair<int, int>> q;
q.push({x, y});
while (!q.empty()) {
auto head = q.front(); q.pop();
int x = head.first;
int y = head.second;
if (grid[x][y] != '1') continue;
grid[x][y] = '0';
for (auto d : dirs) {
int i = x + d.first;
int j = y + d.second;
if (i < 0 || i >= M || j < 0 || j >= N || grid[i][j] != '1') {
continue;
}
q.push({i, j});
}
}
}
private:
vector<pair<int, int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
};
日期
2018 年 7 月 20 日 —— 北京的阴雨天,又闷又潮
2019 年 1 月 8 日 —— 别熬夜,我都开始有黑眼圈了。。
2020 年 4 月 20 日 —— 没想到我也会熬夜看剧
【LeetCode】200. Number of Islands 岛屿数量的更多相关文章
- LeetCode 200. Number of Islands 岛屿数量(C++/Java)
题目: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is s ...
- [leetcode]200. Number of Islands岛屿数量
dfs的第一题 被边界和0包围的1才是岛屿,问题就是分理出连续的1 思路是遍历数组数岛屿,dfs四个方向,遇到1后把周围连续的1置零,代表一个岛屿. /* 思路是:遍历二维数组,遇到1就把周围连续的1 ...
- [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 surro ...
- [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 surro ...
- leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions
两种方式处理已经访问过的节点:一种是用visited存储已经访问过的1:另一种是通过改变原始数值的值,比如将1改成-1,这样小于等于0的都会停止. Number of Islands 用了第一种方式, ...
- [LeetCode] 0200. Number of Islands 岛屿的个数
题目 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is su ...
- Java for 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 surro ...
- (BFS/DFS) 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 surro ...
- 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 surro ...
随机推荐
- rabbit mq的php使用 php-amqplib操作消息队列
rabbit mq的php使用 php-amqplib操作消息队列 有大神翻译的教程,非常清楚可以参考: https://xiaoxiami.gitbook.io/rabbitmq_into_chin ...
- python基础实战
字符串的互相转换 字典的排序 字典的排序可以直接把,key值或者,values拿出来排序 也可以用dict.items拿出所有的key,value的值再加key=lambda x:x[1] 来排序. ...
- 一文搞懂指标采集利器 Telegraf
作者| 姜闻名 来源|尔达 Erda 公众号 导读:为了让大家更好的了解 MSP 中 APM 系统的设计实现,我们决定编写一个<详聊微服务观测>系列文章,深入 APM 系统的产品.架构 ...
- InnoDB学习(二)之ChangeBuffer
ChangeBuffer是InnoDB缓存区的一种特殊的数据结构,当用户执行SQL对非唯一索引进行更改时,如果索引对应的数据页不在缓存中时,InnoDB不会直接加载磁盘数据到缓存数据页中,而是缓存对这 ...
- LeetCode382-链表随机节点
原题链接:[382. 链表随机节点]:https://leetcode-cn.com/problems/linked-list-random-node/ 题目描述: 给定一个单链表,随机选择链表的一个 ...
- display:inline-block,block,inline元素的区别
1.display:block将元素显示为块级元素,从而可以更好地操控元素的宽高,以及内外边距,每一个块级元素都是从新的一行开始.2.display : inline将元素显示为行内元素,高度,行高以 ...
- 如何用shell脚本分析网站日志统计PV、404、500等数据
以下shell脚本能统计出网站的总访问量,以及404,500出现的次数.统计出来后,可以结合监控宝来进行记录,进而可以看出网站访问量是否异常,是否存在攻击.还可以根据查看500出现的次数,进而判断网站 ...
- 【JS】原生实现拖拽
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...
- 04 - Vue3 UI Framework - 文档页
官网的首页做完了,接下来开始做官网的文档页 返回阅读列表点击 这里 路由设计 先想想我们需要文档页通向哪些地方,这里直接给出我的设计: 所属 子标题 跳转路径 文件名(*.vue) 指南 介绍 /do ...
- win10 安装xmemcache及使用
一.下载链接 链接:https://pan.baidu.com/s/14J6Vc8TBEZeRoMp2MgcydQ 提取码:3q8r 二.安装 安装: memcached -d install 卸载 ...