oneby7

Graphs Union-find

464. Making A Large Island

Hard

You are given a square map as a grid of integers, grid, with n rows and n columns. A cell that holds 1 is land, and a cell that holds 0 is water.

An island is a group of land cells joined by steps up, down, left or right. Two land cells that touch only at a corner are not joined. The size of an island is the number of land cells in it.

You may turn at most one water cell into land. Return the size of the largest island the grid can have after that change.

Example 1

1101100101101001

Input: grid = [[1, 1, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0], [1, 0, 0, 1]]

Output: 7

Explanation: Turn the water at row 2, column 0 into land. It joins the 3-cell island above it, the 2-cell island to its right and the 1-cell island below it, so the new island has 3 + 2 + 1 + 1 = 7 cells.

Example 2

1111

Input: grid = [[1, 1], [1, 1]]

Output: 4

Explanation: There is no water to turn into land. The whole grid is already one island of 4 cells.

Example 3

000000000

Input: grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Output: 1

Explanation: Whichever cell we turn into land, it becomes an island of 1 cell on its own.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 500
  • grid[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.