Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Making A Large Island

Hard Acceptance 52.36% Points 40.00

You are given an n x n binary matrix grid[][]. You are allowed to change at most one 0 to 1. A group of connected 1s forms an island. Two 1s are connected if they share one of their sides with each other.

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

Examples
Example 1

Example 1

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

Output: 3

Explanation: Change any one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2

Example 2

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

Output: 4

Explanation: Change the only 0 to 1 and make the island bigger, then we get an island with area = 4.

Hints
Hint 1
Time Complexity: O(N^2)
Hint 2
Space Complexity: O(N^2)
Constraints
  • 1 <= n <= 500
  • 0 <= grid[i][j] <= 1
Companies
Walmart Intuit Infosys
Topics
Graph BFS DFS
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions