Graphs Union-find
464. Making A Large Island
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
Input: grid = [[1, 1, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0],
[1, 0, 0, 1]]
7Explanation: 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
Input: grid = [[1, 1], [1, 1]]
4Explanation: There is no water to turn into land. The whole grid is already one island of 4 cells.
Example 3
Input: grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
1Explanation: 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.
Constraints
n == grid.length == grid[i].length1 ≤ n ≤ 500grid[i][j]is 0 or 1.
Clarifying questions
What you would ask an interviewer before writing any code.