You get a grid where each cell is land (1) or water (0). Return how many islands the grid has.
Land cells that share a side (up, down, left or right) belong to the same island. Cells that meet only at a corner don't. Everything around the grid is water.
Example 1:
Input: 0 1 1 0 0 0 1 0 0 1 1 1 0 1 1 1 0 0 0 1 Output: 2 Explanation: The green island and the blue island never share a side.
Example 2:
Input: 1 1 0 0 1 0 0 1 0 1 0 1 0 0 0 Output: 4 Explanation: The red cell and the orange cell touch other land only at corners. So each of them is an island of its own.
Example 3:
Input: 0 0 0 0 0 0 Output: 0 Explanation: There is no land at all.
Constraints:
- 1 to 100 rows.
- 1 to 100 columns.
- Every cell is
0or1.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Solution #1 · O(n * m)
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
