["110", "010", "001"]→ 2The upper-left land is one group. The lower-right land touches it only diagonally, so it is separate.
Count groups of land in a rectangular grid. A land cell connects to land directly above, below, left, or right; diagonal contact alone does not connect two groups.
["110", "010", "001"]→ 2The upper-left land is one group. The lower-right land touches it only diagonally, so it is separate.
["111", "010", "111"]→ 1The center column joins the upper and lower rows into a single group.
["000", "000"]→ 0There is no land cell that can start an island.
For each land cell, independently search for all land reachable from it and compare those reachable sets. This repeats the same exploration many times and can approach quadratic work in the number of cells.
Scan the grid. When you find land not yet visited, count one new island and traverse from it using a stack or queue. Mark land as visited when adding it to the frontier so it cannot be scheduled twice. The traversal consumes that whole component before the scan continues.
Before each new scan position, every visited land cell belongs to an island already counted. A new unvisited land cell therefore starts a different island. Four-direction traversal marks exactly the cells connected to that start, so no group is counted twice or skipped.
For m rows and n columns, the scan and traversal together inspect each cell a constant number of times: O(mn) time. The visited set and frontier can each hold O(mn) cells in the worst case.
In ["10", "01"], the two 1 cells touch diagonally but not orthogonally. An eight-direction flood fill would return one island; the required answer is two.
Each new unvisited land cell starts a group. Follow four-direction neighbors and notice that diagonal contact does not join groups.
Inspect row 1, column 1. Frontier: (1, 2).
This unvisited land starts island 1. Mark it before exploring neighbors.These choices help you inspect the reasoning. A separate coding pass records an independent solve.
Write solve(grid). grid is an array of equal-length strings made of 0 and 1. Return the number of four-direction land components without modifying grid. The local checks include empty, diagonal, and irregular grids.
Opening the code studio…
Loading your saved attempts…
For additional practice, see the related LeetCode challenge.