๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 200 - Number of Islands (Medium)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 200๋ฒˆ

ํ’€์ด ๊ณผ์ •

์„ฌ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด์ฃผ๋Š” DFS ํƒ์ƒ‰ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์ด์ง€๋งŒ ํžˆ๋“  ์ผ€์ด์Šค ๋•Œ๋ฌธ์— ์กฐ๊ธˆ ํ—ค๋งธ์Šต๋‹ˆ๋‹ค.

LeetCode ๋ฌธ์ œ๋Š” ๊น”๋”ํ•˜์ง€๋งŒ ์ž…๋ ฅ ์ œํ•œ ์‚ฌํ•ญ์ด ๋ช…์‹œ๋˜์–ด์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ์–ด์„œ ๋‚œ๊ฐํ•œ ์ƒํ™ฉ์ด ์ข…์ข… ๋ฐœ์ƒํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
(์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” grid ๊ฐ€ ๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•  ๊ฒƒ์ด๋ผ๊ณ  ์ƒ๊ฐ์„ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค..)

๋•Œ๋ฌธ์— ๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ๋Š” ์—ฌ๋Ÿฌ edge case ๋ฅผ ๊ณ ๋ คํ•˜๋Š” ์—ฐ์Šต์ด ํ•„์š”ํ•ด๋ณด์ž…๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
  const dx = [0, 0, 1, -1];
  const dy = [1, -1, 0, 0];

  if (!grid.length) {
    return 0;
  }

  const N = grid.length,
    M = grid[0].length;
  const visit = new Array(N).fill(0).map((_) => new Array(M));

  function dfs(x, y) {
    visit[x][y] = 1;

    for (let i = 0; i < 4; i++) {
      let nx = x + dx[i],
        ny = y + dy[i];
      if (0 <= nx && nx < N && 0 <= ny && ny < M) {
        if (!visit[nx][ny] && grid[nx][ny] === "1") {
          dfs(nx, ny);
        }
      }
    }
  }

  let ans = 0;
  for (let x = 0; x < grid.length; x++) {
    for (let y = 0; y < grid[0].length; y++) {
      if (!visit[x][y] && grid[x][y] === "1") {
        dfs(x, y);
        ans++;
      }
    }
  }

  return ans;
};

const grid = [
  ["1", "1", "0", "0", "0"],
  ["1", "1", "0", "0", "0"],
  ["0", "0", "1", "0", "0"],
  ["0", "0", "0", "1", "1"],
];

console.log(numIslands(grid));
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 1094 - Car Pooling (Medium)  (0) 2021.03.02
LeetCode 49 - Group Anagrams (Medium)  (0) 2021.03.02
LeetCode 64 - Minimum Path Sum (Medium)  (0) 2021.03.02
LeetCode 55 - Jump Game (Medium)  (0) 2021.03.02
LeetCode 70 - Climing Stairs (Easy)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€