Skip to content

Commit de439d0

Browse files
author
hasibulislam999
committed
Number of Closed Islands problem solved
1 parent f944d88 commit de439d0

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Easy/1254_number-of-closed-islands.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Title: Number of Closed Islands
3+
* Description: Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
4+
* Author: Hasibul Islam
5+
* Date: 06/04/2023
6+
*/
7+
8+
/**
9+
* @param {number[][]} grid
10+
* @return {number}
11+
*/
12+
var closedIsland = function (grid) {
13+
const R = grid.length,
14+
C = grid[0].length;
15+
const dir = [
16+
[1, 0],
17+
[-1, 0],
18+
[0, 1],
19+
[0, -1],
20+
];
21+
let counter = 0;
22+
23+
for (let r = 1; r < R - 1; r++) {
24+
for (let c = 1; c < C - 1; c++) {
25+
if (!grid[r][c] && isValid(r, c)) counter++;
26+
}
27+
}
28+
return counter;
29+
30+
function isValid(r, c) {
31+
if (grid[r][c]) return true;
32+
if (r == 0 || c == 0 || r == R - 1 || c == C - 1) return false;
33+
grid[r][c] = 1;
34+
35+
let result = true;
36+
37+
for (let [dr, dc] of dir) {
38+
if (!isValid(dr + r, dc + c)) result = false;
39+
}
40+
return result;
41+
}
42+
};
43+
44+
console.log(
45+
closedIsland([
46+
[1, 1, 0, 0, 0],
47+
[1, 1, 0, 0, 0],
48+
[0, 0, 0, 1, 1],
49+
[0, 0, 0, 0, 0],
50+
[0, 0, 0, 0, 0],
51+
])
52+
);

0 commit comments

Comments
 (0)