462/670

462. Max Area of Island

Medium

You are given an m × n grid of characters where '1' is land and '0' is water. An island is a maximal group of land cells connected up, down, left, or right — diagonal contact does not connect cells.

The area of an island is how many cells it contains. Return the area of the largest island in the grid, or 0 if there is no land at all.

Example 1 — the largest islandThe gold 2×2 block is the largest island: area 4. The muted islands measure 2, 1, and 1 — the single cell at the right edge touches the block only diagonally, which does not count as connected.
largest island — area 4other islands: 2, 1, 1diagonal touch ≠ connected

Example 1:

Input: grid = ["01100", "01101", "00010", "10010"]

Output: 4

Explanation: The 2×2 block near the top left has 4 cells. The other islands have areas 1, 2, and 1 — note the lone cell at (1,4) touches the block only diagonally, so it does not join it.

Example 2:

Input: grid = ["000", "000", "000"]

Output: 0

Explanation: All water — there is no island, so the answer is 0.

Constraints:

  • 1 ≤ m, n ≤ 50
  • grid[i][j] is '0' or '1'

Hints:

Islands are connected components. From any land cell, a flood fill (DFS or BFS) can visit its whole island exactly once — and can count cells while it goes.

Scan the grid; every time you stand on unvisited land, flood-fill from there, sinking each visited cell (flip it to '0' or mark it) so no island is ever measured twice. Keep the running maximum of the flood sizes.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: grid = ["01100", "01101", "00010", "10010"]

Expected output: 4