Number of Islands

#DFS #UnionFind

Question

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.

Tags

Facebook Zenefits Google

Related Problems

Medium Surrounded Regions Hard Number of Islands II

Analysis

思路一: 此题可以考虑用Union Find,不过更简单的是用BFS或者DFS。 其中DFS结合mark的方法最巧妙简单,n^2循环,扫描grid[i][j], 如果是island的,即grid[i][j] == true,则计数加一(ans++),并对四个方向进行DFS查找,并将所有属于那坐岛屿的点mark为非岛屿。这样扫描过的地方全部会变成非岛屿,而岛屿的数量已被记录。

思路二: Union Find 利用Union Find的find和union操作,对岛屿进行合并计数。因为UnionFind结构一般来说是一维的

表达了如下的连通结构

因此可以转换二维矩阵坐标为一维数字,M N 的矩阵中`(i,j) -> i N + j`。

  1. 建立UnionFind的parent[] (或者 parent hashmap),初始化各个parent[i * N + j] = i * N + j,如果grid[i][j] == true,则岛屿计数count++

  2. 之后再对矩阵遍历一次,当遇到岛屿时,则要检查上下左右四个方向的邻近点,如果也是岛屿则合并,并且count--;

Union Find结构可以用Path Compression和Weighted Union进行优化。

Solution

DFS (3ms AC)

DFS (same, just with directional 2D array)

BFS - (14ms AC)

BFS - (17ms AC)

Union Find (Verbose, 19 ms AC)

Another Union Find (8ms AC)

Solution

Last updated

Was this helpful?