Island Counter
Given a 2D matrix where each element is either '1' (representing land) or '0' (representing water), count the number of islands in this matrix. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the matrix are surrounded by water.
[ [ "1", "1", "0", "0", "0" ], [ "1", "1", "0", "0", "0" ], [ "0", "0", "1", "0", "0" ], [ "0", "0", "0", "1", "1" ] ]
Explanation. There are three islands. Two '1's connected in the top two rows, a single '1' as an island in the middle, and two '1's connected at the bottom right.
[ [ "1", "0", "0", "1", "1" ], [ "0", "0", "1", "0", "1" ], [ "1", "0", "1", "0", "0" ], [ "1", "1", "0", "0", "0" ] ]
Explanation. Each separated group of '1's represents an island. There are six isolated groups.
Follow-up: Could you modify your solution to handle diagonally adjacent lands as part of the same island?
The matrix will not be empty and will always contain at least one row and one column. Elements are only '1' or '0'.
- Views
- 2