@@ -605,6 +605,63 @@ func bfs(grid [][]int, i, j int) {
605605}
606606```
607607
608+ ### JavaScript
609+
610+ ``` js
611+ /**
612+ * @param {number[][]} grid
613+ * @return {number}
614+ */
615+ var numEnclaves = function (grid ) {
616+ let row = grid .length ;
617+ let col = grid[0 ].length ;
618+ let count = 0 ;
619+
620+ // Check the first and last row, if there is a 1, then change all the connected 1s to 0 and don't count them.
621+ for (let j = 0 ; j < col; j++ ) {
622+ if (grid[0 ][j] === 1 ) {
623+ dfs (0 , j, false );
624+ }
625+ if (grid[row - 1 ][j] === 1 ) {
626+ dfs (row - 1 , j, false );
627+ }
628+ }
629+
630+ // Check the first and last column, if there is a 1, then change all the connected 1s to 0 and don't count them.
631+ for (let i = 0 ; i < row; i++ ) {
632+ if (grid[i][0 ] === 1 ) {
633+ dfs (i, 0 , false );
634+ }
635+ if (grid[i][col - 1 ] === 1 ) {
636+ dfs (i, col - 1 , false );
637+ }
638+ }
639+
640+ // Check the rest of the grid, if there is a 1, then change all the connected 1s to 0 and count them.
641+ for (let i = 1 ; i < row - 1 ; i++ ) {
642+ for (let j = 1 ; j < col - 1 ; j++ ) {
643+ dfs (i, j, true );
644+ }
645+ }
646+
647+ function dfs (i , j , isCounting ) {
648+ let condition = i < 0 || i >= grid .length || j < 0 || j >= grid[0 ].length || grid[i][j] === 0 ;
649+
650+ if (condition) return ;
651+ if (isCounting) count++ ;
652+
653+ grid[i][j] = 0 ;
654+
655+ dfs (i - 1 , j, isCounting);
656+ dfs (i + 1 , j, isCounting);
657+ dfs (i, j - 1 , isCounting);
658+ dfs (i, j + 1 , isCounting);
659+ }
660+
661+ return count;
662+ };
663+ ```
664+
608665### Rust
609666
610667dfs:
@@ -700,3 +757,4 @@ impl Solution {
700757<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
701758 <img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
702759</a >
760+
0 commit comments