From 6ef77329949055714d0d263ff762e898ac38233d Mon Sep 17 00:00:00 2001 From: Nicolas Leigh Date: Sun, 26 May 2024 11:07:12 +0800 Subject: [PATCH] =?UTF-8?q?Add=20JavaScript=20solution=20to=20the=20proble?= =?UTF-8?q?m=201020.=E9=A3=9E=E5=9C=B0=E7=9A=84=E6=95=B0=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...60\347\232\204\346\225\260\351\207\217.md" | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git "a/problems/1020.\351\243\236\345\234\260\347\232\204\346\225\260\351\207\217.md" "b/problems/1020.\351\243\236\345\234\260\347\232\204\346\225\260\351\207\217.md" index 59610c6801..5f1995a5ce 100644 --- "a/problems/1020.\351\243\236\345\234\260\347\232\204\346\225\260\351\207\217.md" +++ "b/problems/1020.\351\243\236\345\234\260\347\232\204\346\225\260\351\207\217.md" @@ -605,6 +605,63 @@ func bfs(grid [][]int, i, j int) { } ``` +### JavaScript + +```js +/** + * @param {number[][]} grid + * @return {number} + */ +var numEnclaves = function (grid) { + let row = grid.length; + let col = grid[0].length; + let count = 0; + + // Check the first and last row, if there is a 1, then change all the connected 1s to 0 and don't count them. + for (let j = 0; j < col; j++) { + if (grid[0][j] === 1) { + dfs(0, j, false); + } + if (grid[row - 1][j] === 1) { + dfs(row - 1, j, false); + } + } + + // Check the first and last column, if there is a 1, then change all the connected 1s to 0 and don't count them. + for (let i = 0; i < row; i++) { + if (grid[i][0] === 1) { + dfs(i, 0, false); + } + if (grid[i][col - 1] === 1) { + dfs(i, col - 1, false); + } + } + + // Check the rest of the grid, if there is a 1, then change all the connected 1s to 0 and count them. + for (let i = 1; i < row - 1; i++) { + for (let j = 1; j < col - 1; j++) { + dfs(i, j, true); + } + } + + function dfs(i, j, isCounting) { + let condition = i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] === 0; + + if (condition) return; + if (isCounting) count++; + + grid[i][j] = 0; + + dfs(i - 1, j, isCounting); + dfs(i + 1, j, isCounting); + dfs(i, j - 1, isCounting); + dfs(i, j + 1, isCounting); + } + + return count; +}; +``` + ### Rust dfs: @@ -700,3 +757,4 @@ impl Solution { +