From 6d18cb0d950c964ccc9a1c4d8dcc1161301fbaec Mon Sep 17 00:00:00 2001 From: bangdori Date: Thu, 12 Jun 2025 11:33:36 +0900 Subject: [PATCH] =?UTF-8?q?[=EA=B0=95=EB=B3=91=EC=A4=80]=20Number=20of=20I?= =?UTF-8?q?slands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bangdori/200.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 bangdori/200.js diff --git a/bangdori/200.js b/bangdori/200.js new file mode 100644 index 0000000..6560736 --- /dev/null +++ b/bangdori/200.js @@ -0,0 +1,48 @@ +const LAND = "1"; +const WATER = "0"; + +const dirs = [ + [-1, 0], + [1, 0], + [0, 1], + [0, -1], +]; + +/** + * @param {character[][]} grid + * @return {number} + */ +var numIslands = function (grid) { + const ySize = grid.length; + const xSize = grid[0].length; + + const visited = Array.from({ length: ySize }, () => Array(xSize).fill(false)); + let answer = 0; + + const dfs = (y, x) => { + if (visited[y][x]) return; + + visited[y][x] = true; + + for (let [dy, dx] of dirs) { + const ny = y + dy; + const nx = x + dx; + + if (ny < 0 || ny >= ySize || nx < 0 || nx >= xSize) continue; + if (visited[ny][nx] || grid[ny][nx] === WATER) continue; + + dfs(ny, nx); + } + }; + + for (let y = 0; y < ySize; y++) { + for (let x = 0; x < xSize; x++) { + if (visited[y][x] || grid[y][x] === WATER) continue; + + answer++; + dfs(y, x); + } + } + + return answer; +};