Skip to content

Commit c2b1a78

Browse files
committed
Add solution #1020
1 parent 9e8335d commit c2b1a78

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,094 LeetCode solutions in JavaScript
1+
# 1,095 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -828,6 +828,7 @@
828828
1017|[Convert to Base -2](./solutions/1017-convert-to-base-2.js)|Medium|
829829
1018|[Binary Prefix Divisible By 5](./solutions/1018-binary-prefix-divisible-by-5.js)|Easy|
830830
1019|[Next Greater Node In Linked List](./solutions/1019-next-greater-node-in-linked-list.js)|Medium|
831+
1020|[Number of Enclaves](./solutions/1020-number-of-enclaves.js)|Medium|
831832
1022|[Sum of Root To Leaf Binary Numbers](./solutions/1022-sum-of-root-to-leaf-binary-numbers.js)|Easy|
832833
1023|[Camelcase Matching](./solutions/1023-camelcase-matching.js)|Medium|
833834
1028|[Recover a Tree From Preorder Traversal](./solutions/1028-recover-a-tree-from-preorder-traversal.js)|Hard|

solutions/1020-number-of-enclaves.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 1020. Number of Enclaves
3+
* https://leetcode.com/problems/number-of-enclaves/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents
7+
* a land cell.
8+
*
9+
* A move consists of walking from one land cell to another adjacent (4-directionally) land cell
10+
* or walking off the boundary of the grid.
11+
*
12+
* Return the number of land cells in grid for which we cannot walk off the boundary of the grid
13+
* in any number of moves.
14+
*/
15+
16+
/**
17+
* @param {number[][]} grid
18+
* @return {number}
19+
*/
20+
var numEnclaves = function(grid) {
21+
const rows = grid.length;
22+
const cols = grid[0].length;
23+
24+
for (let i = 0; i < rows; i++) {
25+
exploreBoundary(i, 0);
26+
exploreBoundary(i, cols - 1);
27+
}
28+
29+
for (let j = 0; j < cols; j++) {
30+
exploreBoundary(0, j);
31+
exploreBoundary(rows - 1, j);
32+
}
33+
34+
let result = 0;
35+
for (let i = 0; i < rows; i++) {
36+
for (let j = 0; j < cols; j++) {
37+
result += grid[i][j];
38+
}
39+
}
40+
41+
return result;
42+
43+
function exploreBoundary(row, col) {
44+
if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 1) return;
45+
grid[row][col] = 0;
46+
exploreBoundary(row + 1, col);
47+
exploreBoundary(row - 1, col);
48+
exploreBoundary(row, col + 1);
49+
exploreBoundary(row, col - 1);
50+
}
51+
};

0 commit comments

Comments
 (0)