FastPrepLargest Island After One Land Conversion

Largest Island After One Land Conversion

Google logoGoogle● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

You are given an n x n binary matrix grid. You may change at most one 0 into 1.

An island is a four-directionally connected group of 1s. Return the largest island area obtainable after the optional conversion.

Function

largestIsland(grid: int[][]) → int

Examples

Example 1

grid = [[1,0],[0,1]]return = 3

Changing either zero joins the two diagonal land cells through the converted cell.

Example 2

grid = [[1,1],[1,0]]return = 4

Changing the only zero makes the whole grid one island.

Example 3

grid = [[1,1],[1,1]]return = 4

The grid is already one island, so no conversion is needed.

Constraints

  • 1 <= n <= 500.
  • n == grid.length == grid[i].length.
  • grid[i][j] is 0 or 1.
  • Four-directional adjacency defines an island.

More Google problems

See Google hiring insights
public int largestIsland(int[][] grid) {
    // Write your code here.
}
grid[[1,0],[0,1]]
expected3
Checking account…