Skip to content

Commit 6d40d4a

Browse files
committed
Add solution #827
1 parent da0283c commit 6d40d4a

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@
311311
819|[Most Common Word](./0819-most-common-word.js)|Easy|
312312
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
313313
824|[Goat Latin](./0824-goat-latin.js)|Easy|
314+
827|[Making A Large Island](./0827-making-a-large-island.js)|Hard|
314315
831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium|
315316
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
316317
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* 827. Making A Large Island
3+
* https://leetcode.com/problems/making-a-large-island/
4+
* Difficulty: Hard
5+
*
6+
* You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
7+
*
8+
* Return the size of the largest island in grid after applying this operation.
9+
*
10+
* An island is a 4-directionally connected group of 1s.
11+
*/
12+
13+
/**
14+
* @param {number[][]} grid
15+
* @return {number}
16+
*/
17+
var largestIsland = function(grid) {
18+
function traverse(tile, grid, i, j) {
19+
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length
20+
|| grid[i][j] === 0 || grid[i][j] === tile) {
21+
return 0;
22+
}
23+
grid[i][j] = tile;
24+
return 1 + (
25+
traverse(tile, grid, i + 1, j)
26+
+ traverse(tile, grid, i - 1, j)
27+
+ traverse(tile, grid, i, j + 1)
28+
+ traverse(tile, grid, i, j - 1)
29+
);
30+
};
31+
32+
const map = new Map();
33+
let tile = 2;
34+
let result = -1;
35+
36+
for (let i = 0; i < grid.length; i++) {
37+
for (let j = 0; j < grid.length; j++) {
38+
if (grid[i][j] === 1) {
39+
const value = traverse(tile, grid, i, j);
40+
map.set(tile, value);
41+
tile += 1;
42+
result = Math.max(result, value);
43+
}
44+
}
45+
}
46+
47+
map.set(0, 0);
48+
49+
for (let i = 0; i < grid.length; i++) {
50+
for (let j = 0; j < grid.length; j++) {
51+
if (!grid[i][j]) {
52+
const seen = new Set();
53+
let sum = 0;
54+
if (i > 0) seen.add(grid[i - 1][j]);
55+
if (j > 0) seen.add(grid[i][j - 1]);
56+
if (i < grid.length - 1) seen.add(grid[i + 1][j]);
57+
if (j < grid.length - 1) seen.add(grid[i][j + 1]);
58+
seen.forEach(val => sum += map.get(val));
59+
result = Math.max(result, sum + 1);
60+
}
61+
}
62+
}
63+
64+
return result;
65+
};

0 commit comments

Comments
 (0)