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.

Example

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的更多相关文章

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

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

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

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

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

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

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

  8. LeetCode 305. Number of Islands II

    原题链接在这里:https://leetcode.com/problems/number-of-islands-ii/ 题目: A 2d grid map of m rows and n column ...

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

随机推荐

  1. wordpress学习三:wordpress自带的模板学习

    在<学习二>里,大概说了下怎么去查找模板,本节我们以一个简单的模板为例子,继续说说wordpress的模板机制,看看做一个自己的模板需要哪些知识点. 页面模板渲染 wordpress的模板 ...

  2. Opendaylight的Carbon(碳)版本安装

    Opendaylight Carbon(碳)版本安装 1.更新源 sudo apt-get update sudo apt-get upgrade 2.安装JDK1.8 sudo apt-get in ...

  3. Objective-C runtime 机制

    Runtime使用C语言结构体表示对象,用C语言函数表示方法,这些C语言函数和结构体被Runtime封装后,我们就可以在程序中执行创建,检查,修改类和对象和他们的方法 OC的Class其实是一个obj ...

  4. C#简述(三)

    详细请参考:http://www.runoob.com/csharp/csharp-string.html 1.C# 字符串(String) 在 C# 中,可以使用字符数组来表示字符串,但是,更常见的 ...

  5. formidable模块的使用

    Node.js的Formidable模块的使用   今天总结了下Node.js的Formidable模块的使用,下面做一些简要的说明. 1)     创建Formidable.IncomingForm ...

  6. 如何有效地让一个“ParentFont = False”子控件使用与父母相同的字体名称?

    如何有效地让一个“ParentFont = False”子控件使用与父母相同的字体名称?(How to efficiently let a `ParentFont = False` child con ...

  7. Hello 2019 自闭记

    A:8min才过??? #include<iostream> #include<cstdio> #include<cmath> #include<cstdli ...

  8. BZOJ 2125: 最短路

    2125: 最短路 Time Limit: 1 Sec  Memory Limit: 259 MBSubmit: 756  Solved: 331[Submit][Status][Discuss] D ...

  9. HDU 4303 Hourai Jeweled 解题报告

    HDU 4303 Hourai Jeweled 解题报告 评测地址: http://acm.hdu.edu.cn/showproblem.php?pid=4303 评测地址: https://xoj. ...

  10. 洛谷 P1852 [国家集训队]跳跳棋 解题报告

    P1852 [国家集训队]跳跳棋 题目描述 跳跳棋是在一条数轴上进行的.棋子只能摆在整点上.每个点不能摆超过一个棋子. 我们用跳跳棋来做一个简单的游戏:棋盘上有3颗棋子,分别在\(a\),\(b\), ...