← Whiteboard questions

Max Area of Island

Find the size of the largest island on a map

DSA, Medium, Graphs

Which structure or algorithm, and what does it cost.

A map is a list of strings of equal length. # is land and . is water. Two land cells touch if they share a side: up, down, left or right. A diagonal touch does not count. An island is a group of land cells that touch in a chain. Write biggest_island(grid). It returns the number of cells in the largest island, or 0 if the map has no land.

Examples

Input grid = ["#.#..", "##...", "...##", "..###"]
Output 5
Why the islands have 3, 1 and 5 cells, and the largest has 5.
Input grid = ["...", "..."]
Output 0
Why there is no land.
Input grid = ["#.", ".#"]
Output 1
Why the two land cells meet only at a corner, so each island has 1 cell.

Constraints

Your answer must contain

Target Aim for O(R * C) time and memory, where R is the number of rows and C the number of columns.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at one land cell. Which cells belong to its island, and how can you collect them all without counting any cell twice?

Hint 2 the approach

Start a search at a land cell you have not visited. Spread to touching land cells and mark each as visited. When the search ends, you have one whole island.

Hint 3 the key step

Count the cells each search visits and keep the largest count. Mark a cell visited when you add it to the stack, not when you take it out.

Walkthrough

Full walkthrough brute force to best

Brute force

For every land cell, start a fresh search that counts the land cells it can reach, with its own visited marks. A cell in a big island is searched again for every cell of that island. A map that is all land costs O((R * C)^2) time.

Best method

Scan the cells in order. When you meet a land cell that is not visited, start a search there. Mark the cell visited and push it on a stack. Take a cell off the stack and count it. For each of its four neighbours that is inside the map, is land and is not visited, mark it visited and push it. When the stack is empty, the count is the size of that island. Keep the largest count. The marks make every land cell join exactly one search. A stack keeps the search a loop, so a 300 by 300 island cannot overflow the call stack.

Hand trace

Example 1: the scan meets land at (0,0) first. That search counts (0,0), (1,0) and (1,1), so the size is 3. The scan then meets land at (0,2), which has no land neighbour, so the size is 1. The cells already visited are skipped. The next unvisited land cell is (2,3). That search counts (2,3), (2,4), (3,2), (3,3) and (3,4), so the size is 5. The largest size is 5.

Code

def biggest_island(grid):
    rows, cols = len(grid), len(grid[0])
    seen = [[False] * cols for _ in range(rows)]
    best = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '#' and not seen[r][c]:
                seen[r][c] = True            # mark when pushed, so a cell is counted once
                stack = [(r, c)]
                size = 0
                while stack:
                    y, x = stack.pop()
                    size += 1
                    for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                        if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == '#' and not seen[ny][nx]:
                            seen[ny][nx] = True
                            stack.append((ny, nx))
                best = max(best, size)
    return best

Time and memory

O(R * C) time and O(R * C) memory. Each cell is marked and pushed at most once and looked at from four sides. The visited table and the stack hold up to R * C cells.

Common mistakes

  • Marking a cell visited only when it leaves the stack. A cell can be pushed twice and counted twice, so mark it when you push it.
  • Treating diagonal cells as touching. Only the four side neighbours count.
  • Returning the number of islands, or the total number of land cells, instead of the size of the largest island.

Related problems

More Graphs problems
Max Area of Island: hints, walkthrough and Python solution