16. Making A Large Island
The problem can be found at the following link: Question Link
My Approach
To solve this problem, we first have to identify each island in the grid and calculate its size using Depth-First Search (DFS).
Then assign a unique identifier to each island and store the size of each island in a hashmap.
Then, I iterate through the grid again and, for each water cell
0
,I check its neighbouring islands, calculate the combined size of these neighbouring islands, and determine the maximum size of an island that can be created by changing this water cell to land.
I keep track of the maximum island size found during this process.
Explain with example
Consider the following grid where 1 represents land and 0 represents water:
Time and Auxiliary Space Complexity
Time Complexity:
O(N^2)
, whereN
is the size of the grid.Auxiliary Space Complexity:
O(N^2)
for the hashmap to store island sizes.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated