Skip to content

827. Making A Large Island

Difficulty Topics

Description

You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

Return the size of the largest island in grid after applying this operation.

An island is a 4-directionally connected group of 1s.

 

Example 1:

Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:

Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.

Example 3:

Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.

 

Constraints:

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

Solution

making-a-large-island.py
class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        mp = collections.defaultdict(int)
        colorIndex = 2

        def dfs(x, y, color):
            size = 1
            grid[x][y] = color

            for dx, dy in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
                if 0 <= dx < rows and 0 <= dy < cols and grid[dx][dy] == 1:
                    size += dfs(dx, dy, color)

            return size

        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == 1:
                    size = dfs(i, j, colorIndex)
                    mp[colorIndex] = size
                    colorIndex += 1

        res = mp[2]
        for x in range(rows):
            for y in range(cols):
                if grid[x][y] == 0:
                    size = 1
                    sset = set()

                    for dx, dy in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
                        if 0 <= dx < rows and 0 <= dy < cols and grid[dx][dy] not in sset:
                            size += mp[grid[dx][dy]]
                            sset.add(grid[dx][dy])

                    res = max(res, size)

        return res