Number of Islands
Given a boolean 2D matrix,0is represented as the sea,1is 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
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]
]return3.
Note
经典题,很多01矩阵题的原型都是这道题。
本质是寻找联通块的数目,也可以用Union-Find解决,见Number of Islands ii
需要掌握BFS和DFS的方法,在遍历的同时进行改动原值mark by bfs/dfs,dfs会有爆栈的可能,bfs会更好一些
Time: O(MN), Space: O(MN)
Code
Last updated