Number of Islands

update Jul 18, 2017 17:26

lintcodearrow-up-right LeetCodearrow-up-right

Given a boolean 2D matrix, 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.

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]
]
return 3.

Basic Idea:

首先我们可以想到的就是使用一个bfs helper function,对每个原图中为1的点bfs,然后用一个visited set记录是否已经visited。每次成功进入bfs,则ret += 1. 由此思路,我们可以进一步考虑,如果我们不使用额外的visited set,只在原图中改动,其实也可以达到目的,我们只需在每次bfs的时候,将遇到的点全部改为0,这样每次进入bfs的时候即说明当前的1没有被visited,ret++。

具体的我们注意到在处理对上下左右四个方向bfs的时候,为了代码concise,我们使用了rdir 和 cdir两个int[],其实是列出了r和c两个坐标每次的偏移量,

    {-1, 0, 1, 0}
    {0, -1, 0, 1}

其实就表示了下左上右四个方向的相邻坐标点。九章算法中把这个内容叫做坐标变换数组

Java Code:

update 2018-05-19 23:20:30

C++ DFS Solution: