Loading problem...
You are given a two-dimensional binary grid of dimensions m x n, where each cell contains either the character '1' representing solid terrain (land) or the character '0' representing open water.
A landmass is defined as a contiguous region of land cells that are connected horizontally or vertically (not diagonally). In other words, two land cells belong to the same landmass if you can travel from one to the other by moving only up, down, left, or right through adjacent land cells.
You may assume that all cells outside the grid boundaries (beyond the edges) are completely submerged in water, effectively surrounding the entire grid with an ocean.
Your task is to determine the total count of distinct landmasses present in the given grid.
Key Observations:
'1' surrounded by water on all sides constitutes one landmass.'1's forms a single landmass regardless of its shape.grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]1All the land cells in the top-left region are connected horizontally and vertically, forming a single contiguous landmass. The bottom row and rightmost columns are entirely water.
grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]3There are three distinct landmasses: (1) the top-left 2x2 cluster of land cells, (2) the isolated land cell in the middle of the grid, and (3) the two connected land cells in the bottom-right corner. These regions are not connected to each other.
grid = [
["1","0","1"],
["0","0","0"],
["1","0","1"]
]4Each corner has an isolated land cell, and they are separated by water. Diagonal adjacency does not connect landmasses, so each of the four corners is its own distinct landmass.
Constraints