Number of Islands I & II
Given a boolean 2D matrix, find the number of islands.
Notice
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.
Given graph:
[
[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]
]
return 3.
分析:
从第一个数到最后一个数,如果遇到1,则island count 加1, 并且不断递归去寻找周围的1。
public class Solution {
public int numIslands(char[][] grid) {
int count = ;
if (grid == null || grid.length == ) return count;
int m = grid.length, n = grid[].length;
boolean[][] visited = new boolean[m][n];
for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (!visited[i][j] && grid[i][j] == '') {
count++;
flood(i, j, grid, visited);
}
}
}
return count;
}
private void flood(int i, int j, char[][] grid, boolean[][] visited) {
if (i < || i >= grid.length || j < || j >= grid[].length) return;
if (grid[i][j] == '' || visited[i][j]) return;
visited[i][j] = true;
flood(i + , j, grid, visited);
flood(i - , j, grid, visited);
flood(i, j + , grid, visited);
flood(i, j - , grid, visited);
}
}
Follow up:
Find the perimeter of the island. Answer: find the # of 1 which is next to 0.
Number of Islands II
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. 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:
Given m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]].
Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 >represents land).
0 0 0
0 0 0
0 0 0
Operation #1: addLand(0, 0) turns the water at grid0 into a land.
1 0 0
0 0 0 Number of islands = 1
0 0 0
Operation #2: addLand(0, 1) turns the water at grid0 into a land.
1 1 0
0 0 0 Number of islands = 1
0 0 0
Operation #3: addLand(1, 2) turns the water at grid1 into a land.
1 1 0
0 0 1 Number of islands = 2
0 0 0
Operation #4: addLand(2, 1) turns the water at grid2 into a land.
1 1 0
0 0 1 Number of islands = 3
0 1 0
We return the result as an array: [1, 1, 2, 3]
分析:https://segmentfault.com/a/1190000004197552
很典型的union-find题。因为这里是动态的增加land,要能随时求出有多少个island,最简单的方法就是union-find。我们可以定义一个counter, 每增加一个land, 增加counter, 然后我们搜索那个land邻居区域,发现root不一样的话,意味着可以union, 每union一次,意味着两个island合并成一个,减小counter, 统计最终的counter值,即是增加land后的最终island的个数。
为了减小时间复杂度,代码实现是QuickUnion + Path Compression, Path Compression目的是为了调整树的高度,保持很平的树,而不是越来越高,这样找root不会出现worst case.
public class Solution {
public List<Integer> numIslands2(int m, int n, int[][] positions) {
int[] id = new int[m * n]; // 表示各个index对应的root
Arrays.fill(id, -); // 初始化root为-1,用来标记water, 非-1表示land
List<Integer> res = new ArrayList<>();
int count = ; // 记录island的数量
int[][] dirs = { { -, }, { , }, { , }, { , - } };
for (int i = ; i < positions.length; i++) {
count++;
int index = positions[i][] * n + positions[i][];
id[index] = index; // root初始化
for (int j = ; j < dirs.length; j++) {
int x = positions[i][] + dirs[j][];
int y = positions[i][] + dirs[j][];
if (x >= && x < m && y >= && y < n && id[x * n + y] != -) {
int root = root(id, x * n + y); // this is the root of the neibor's islands
// 发现root不等的情况下,才union, 同时减小count。注意,一定要用当前index作为新的root,这样才能保证相连的岛是同一个root。
if (root != index) {
id[root] = index; // set the neighbor's island's root to be the new island index
count--;
}
}
}
res.add(count);
}
return res;
}
public int root(int[] id, int i) {
while (i != id[i]) {
id[i] = id[id[i]]; // 优化,为了减小树的高度
i = id[i];
}
return i;
}
}
Number of Islands I & II的更多相关文章
- [LeetCode] Number of Islands II 岛屿的数量之二
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- [LeetCode] 305. Number of Islands II 岛屿的数量之二
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- [LeetCode] Number of Islands II
Problem Description: A 2d grid map of m rows and n columns is initially filled with water. We may pe ...
- Leetcode: Number of Islands II && Summary of Union Find
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- 305. Number of Islands II
题目: A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand ...
- [Swift]LeetCode305. 岛屿的个数 II $ Number of Islands II
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- LeetCode – Number of Islands II
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- LeetCode 305. Number of Islands II
原题链接在这里:https://leetcode.com/problems/number-of-islands-ii/ 题目: A 2d grid map of m rows and n column ...
- [LeetCode] 305. Number of Islands II 岛屿的数量 II
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
随机推荐
- 老李的blog使用日记(3)
匆匆忙忙.碌碌无为,这是下一个作业,VS,多么神圣高大上,即使这样,有多少人喜欢你就有多少人烦你,依然逃不了被推销的命运,这抑或是它喜欢接受的,但是作为被迫接受者,能做的的也只有接受,而已. 既来之则 ...
- GitHub和Microsoft TFS对比有什么优势
GitHub变得越来越流行,最近Github发布了Github for Windows则大大降低了学习成本和使用难度,它甚至优于TFS. 微软也开始逐渐从TFS向GitHub转移了. 不是 TFS 输 ...
- UIView 添加闪烁的渐变光
CGRect gradientRect=CGRectMake(- imageView3.bounds.size.width*, * imageView3.bounds.size.width, imag ...
- 基于 ARM的 Windows 10S 笔记本 转帖
首款骁龙笔记本华硕畅370评测:续航不俗 性能拖后腿 2018年06月21日 12:23 新浪数码 缩小字体放大字体收藏微博微信分享 相关阅读:国内首款骁龙本华硕畅370发布:6199元送一年无限 ...
- 2 引入jquery和boot
vue引入bootstrap——webpack https://blog.csdn.net/wild46cat/article/details/77662555(copy) 想要在vue中引入boot ...
- java自定义注解学习(三)_注解解析及应用
上篇文章已经介绍了注解的基本构成信息.这篇文章,主要介绍注解的解析.毕竟你只声明了注解,是没有用的.需要进行解析.主要就是利用反射机制在运行时进行查看和利用这些信息 常用方法汇总 在Class.Fie ...
- BOM之navigator对象和用户代理检测
前面的话 navigator对象现在已经成为识别客户端浏览器的事实标准,navigator对象是所有支持javascript的浏览器所共有的.本文将详细介绍navigator对象和用户代理检测 属性 ...
- lightgbm原理以及Python代码
原论文: http://papers.nips.cc/paper/6907-lightgbm-a-highly-efficient-gradient-boosting-decision-tree.pd ...
- 【题解】 Luogu P1402 酒店之王 (二分图匹配)
懒得复制,原题目戳我 Solution: 这题没想到这么水,就是两个二分图而已 如果房间的二分图没匹配成功就直接进入下一个人 如果房间的二分图匹配成功,食物二分图匹配不成功就把房间的\(be[ ]\) ...
- 【UOJ#67】新年的毒瘤(Tarjan)
[UOJ#67]新年的毒瘤(Tarjan) 题面 UOJ 题解 一棵\(n\)个节点的树显然有\(n-1\)条边,在本题中意味着删去一个点之后还剩下\(n-2\)条边.那么找到所有度数为\(m-(n- ...