Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1742 from duanStar/master
Browse files Browse the repository at this point in the history
添加了 1254统计封闭岛屿的数目 js版本
  • Loading branch information
youngyangyang04 authored Nov 21, 2022
2 parents c15b8a7 + 1a854c4 commit ef4cf1a
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions problems/1254.统计封闭岛屿的数目.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,67 @@ public:
return count;
}
};
```
## 其他语言版本
### JavaScript:
```js
/**
* @param {number[][]} grid
* @return {number}
*/
var closedIsland = function(grid) {
let rows = grid.length;
let cols = grid[0].length;
// 存储四个方向
let dir = [[-1, 0], [0, -1], [1, 0], [0, 1]];
// 深度优先
function dfs(x, y) {
grid[x][y] = 1;
// 向四个方向遍历
for(let i = 0; i < 4; i++) {
let nextX = x + dir[i][0];
let nextY = y + dir[i][1];
// 判断是否越界
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) continue;
// 不符合条件
if (grid[nextX][nextY] === 1) continue;
// 继续递归
dfs(nextX, nextY);
}
}
// 从边界岛屿开始
// 从左侧和右侧出发
for(let i = 0; i < rows; i++) {
if (grid[i][0] === 0) dfs(i, 0);
if (grid[i][cols - 1] === 0) dfs(i, cols - 1);
}
// 从上侧和下侧出发
for(let j = 0; j < cols; j++) {
if (grid[0][j] === 0) dfs(0, j);
if (grid[rows - 1][j] === 0) dfs(rows - 1, j);
}
let count = 0;
// 排除所有与边界相连的陆地之后
// 依次遍历网格中的每个元素,如果遇到一个元素是陆地且状态是未访问,则遇到一个新的岛屿,将封闭岛屿的数目加 1
// 并访问与当前陆地连接的所有陆地
for(let i = 0; i < rows; i++) {
for(let j = 0; j < cols; j++) {
if (grid[i][j] === 0) {
count++;
dfs(i, j);
}
}
}
return count;
};
```


<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>


0 comments on commit ef4cf1a

Please sign in to comment.