Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f1c6f81

Browse files
Merge pull request youngyangyang04#2566 from NicolasLeigh/NicolasLeigh-patch-2
Add JavaScript solution to the problem 1020.飞地的数量
2 parents 843c3f7 + 6ef7732 commit f1c6f81

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎problems/1020.飞地的数量.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

610667
dfs:
@@ -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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /