diff --git a/problems/1254.统计封闭岛屿的数目.md b/problems/1254.统计封闭岛屿的数目.md index b70cd496..1270085a 100644 --- a/problems/1254.统计封闭岛屿的数目.md +++ b/problems/1254.统计封闭岛屿的数目.md @@ -81,3 +81,59 @@ public: + +### 其他语言版本 + +### 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; +}; +```