Zepruv › Coding problems

Making A Large Island

Hard · Array, Depth-First Search, Breadth-First Search, Union Find, Matrix

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

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

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

Can't change any 0 to 1, only one island with area = 4.

Constraints

Starter code (python)

class Solution(object):
    def largestIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        

Related problems

Previous: Friends Of Appropriate Ages · Next: Count Unique Characters of All Substrings of a Given String · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.