Count the Separate Landmasses on a Map
Implement countLandmasses
You are given a map of land (1) and water (0) cells. A landmass is a group of land cells connected through shared sides. Count how many separate landmasses the map contains.
A cell that only touches another land cell at a corner is not connected to it. The standard idea is to scan the map and flood-fill each newly found landmass once.
Example 1:
Input: grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,1,0,0]]
Output: 3
Example 2:
Input: grid = [[1,0],[0,1]]
Output: 2
Example 3:
Input: grid = [[0,0,0]]
Output: 0
+ 12 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ rows, cols ≤ 12; grid[r][c] is 1 (land) or 0 (water) - ●
Two land cells belong to the same landmass when you can go from one to the other moving up, down, left or right over land only - ●
Diagonal neighbours are NOT connected - ●
Return the number of landmasses
grid =
[[1,1,0,0], [1,0,0,1], [0,0,1,1], [0,1,0,0]]