827. Making A Large Island
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 1
s.
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 either0
or1
.
Solutions
Solution: Depth-First Search
- Time complexity: O(n2)
- Space complexity: O(n2)
JavaScript
js
/**
* @param {number[][]} grid
* @return {number}
*/
const largestIsland = function (grid) {
const n = grid.length;
const getIslandSize = (row, col, id) => {
if (row < 0 || col < 0 || row >= n || col >= n) return 0;
if (grid[row][col] !== 1) return 0;
grid[row][col] = id;
const top = getIslandSize(row - 1, col, id);
const down = getIslandSize(row + 1, col, id);
const left = getIslandSize(row, col - 1, id);
const right = getIslandSize(row, col + 1, id);
return 1 + top + down + left + right;
};
const islands = Array.from({length: n ** 2 + 2}).fill(0);
let groupId = 2;
for (let row = 0; row < n; row++) {
for (let col = 0; col < n; col++) {
if (!grid[row][col]) continue;
islands[groupId] = getIslandSize(row, col, groupId);
groupId += 1;
}
}
let result = 0;
for (let row = 0; row < n; row++) {
for (let col = 0; col < n; col++) {
if (grid[row][col] > 0) continue;
const top = grid[row - 1]?.[col] ?? 0;
const down = grid[row + 1]?.[col] ?? 0;
const left = grid[row][col - 1] ?? 0;
const right = grid[row][col + 1] ?? 0;
const islandGroups = new Set([top, down, left, right]);
let size = 1;
for (const groupId of islandGroups) {
size += islands[groupId];
}
result = Math.max(size, result);
}
}
return result ? result : n ** 2;
};