Problem
Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. 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 1:
1 |
|
Example 2:
1 |
|
Explanation 1
-
We can use DFS and a visited array to solve this problem.
-
Loop through every element in the two dimensional array, if the element is
1
and it’s not visited, then we start our flood fill dfs helper function to update the visited array. Then, we increase our result counter by 1. -
At the end, we return our result.
Solution 1
1 |
|
Explanation 2
-
We can also use BFS to solve this problem. In order to use BFS, we need a queue. We still need to iterate the 2d grid. When the current grid element is 1, we increase the result by 1 and mark its coordinate in the visited 2d array to true. Then, we push the current grid element’s total value (curRow * numOfColumn + curCol) into the queue.
-
While the queue is not empty, we pop out the total value and use the total value to get back the curRow and curCol. Then we we iterate 4 times, each time we get its updated surrounding position (left, top, right, bottom). If the updated surrounding position is inside the grid and it’s not visited and its value is 1, then we mark the updated position as visited, and then push it to the queue. Repeat until the queue is empty.
Solution 2
1 |
|
Explanation 3
-
This is a disjoin set or union find problem.
-
First, we creat an array
parent[]
that has sizerow * col
, and a variablecnt
. Loop through every element, if the current element is1
, then we increasecnt
and updateparent[i] = i
. -
Next, we loop through every element again, this time if the current element is
1
, then we check its 4 neighbor directions. If its neighbor is not out of bound and its element is also1
, then we find the current element’s parent and its neighbor’s parent. If both parent is not the same, we union both parents and subractcnt
by 1. -
At the end, we return
cnt
as the result.
Solution 3
1 |
|