Skip to content

Commit a0bc879

Browse files
committed
added largestIsland solution
1 parent 6f54e35 commit a0bc879

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Count the number of islands in the given 2D array.
2+
3+
// For Example:
4+
5+
// const matrix = [
6+
// [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
7+
// [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
8+
// [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
9+
// [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
10+
// [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
11+
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
12+
// [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
13+
// [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
14+
// ];
15+
16+
// Output:
17+
// => 6
18+
19+
const test1 = [
20+
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
21+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
22+
[0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
23+
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
24+
[0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
25+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
26+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
27+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
28+
];
29+
30+
const largestIsland = matrix => {
31+
const seen = {};
32+
let maxSize = 0;
33+
for (let r = 0; r < matrix.length; r++) {
34+
for (let c = 0; c < matrix[r].length; c++) {
35+
maxSize = Math.max(calculateSizeOfIsland(r, c, matrix, seen), maxSize);
36+
}
37+
}
38+
return maxSize;
39+
}
40+
41+
const calculateSizeOfIsland = (r, c, matrix, seen) => {
42+
if (
43+
seen[[r,c]] || // already seen
44+
r < 0 || // r is out of bounds
45+
r >= matrix.length || // r is out of bounds
46+
c < 0 || // c is out of bounds
47+
c >= matrix[r].length || // c is out of bounds
48+
matrix[r][c] === 0 // not in an island
49+
) {
50+
return 0;
51+
}
52+
seen[[r,c]] = true;
53+
54+
return (
55+
1 +
56+
calculateSizeOfIsland(r + 1, c, matrix, seen) +
57+
calculateSizeOfIsland(r -1, c, matrix, seen) +
58+
calculateSizeOfIsland(r, c + 1, matrix, seen) +
59+
calculateSizeOfIsland(r, c - 1, matrix, seen)
60+
)
61+
}
62+
63+
console.log(largestIsland(test1)); // 6s

0 commit comments

Comments
 (0)