λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 130 - Surrounded Regions (Medium)

by HandHand 2021. 3. 3.

문제

LeetCode - 130번

풀이 κ³Όμ •

X 둜 λ‘˜λŸ¬μ‹ΈμΈ O 뢀뢄은 λͺ¨λ‘ λ’€μ§‘μ—ˆμ„ λ•Œ μ΅œμ’…μ μœΌλ‘œ μ–΄λ–€ ν˜•νƒœλ₯Ό 가진 board κ°€ λ˜λŠ”μ§€ κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.
μ΄λ•Œ ν•œκ°€μ§€ μ£Όμ˜ν•  점은 λ‘˜λŸ¬μ‹ΈλŠ” ν…Œλ‘λ¦¬κ°€ board 의 경계 μœ„μ— μ‘΄μž¬ν•˜λ©΄ μ•ˆλœλ‹€λŠ” μ μž…λ‹ˆλ‹€.

BFS λ₯Ό μ‚¬μš©ν•˜μ—¬ 문제λ₯Ό ν•΄κ²°ν•˜μ˜€μœΌλ©° ν˜„μž¬ μ’Œν‘œμ—μ„œ μƒν•˜μ’Œμš°λ‘œ μ΄λ™ν–ˆμ„ λ•Œ
board λ₯Ό λ²—μ–΄λ‚˜μ§€ μ•ŠλŠ”μ§€ μ²΄ν¬ν•΄μ„œ 쑰건을 κ²€μ‚¬ν•΄μ€¬μŠ΅λ‹ˆλ‹€.

문제λ₯Ό ν’€λ©΄μ„œ λ°œμƒν–ˆλ˜ 이슈 쀑 ν•˜λ‚˜λŠ” ES6 의 Map μžλ£Œκ΅¬μ‘°μ™€ κ΄€λ ¨λœ λ‚΄μš©μž…λ‹ˆλ‹€.
μ²˜μŒμ—λŠ” λ°©λ¬Έ μ’Œν‘œλ₯Ό λ°°μ—΄ ν‚€κ°’μœΌλ‘œ Map 에 μ €μž₯ν•˜λ €κ³  ν–ˆλŠ”λ° ν…ŒμŠ€νŠΈν•΄λ³΄λ‹ˆκΉŒ
ν‚€ κ°’μœΌλ‘œ 배열을 μ‚¬μš©ν•  경우 μ˜¬λ°”λ₯΄κ²Œ λ™μž‘ν•˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.

(λ§Œμ•½ μ΄λ ‡κ²Œ ν•˜κ³  μ‹ΆμœΌλ©΄ 배열을 λ‹€λ₯Έ λ³€μˆ˜μ— ν• λ‹Ήν•œ λ’€ ν• λ‹Ήλœ λ³€μˆ˜κ°’μ„ ν™œμš©ν•΄ ν‚€λ‘œ μ§€μ •ν•˜κ³ 
has, get λ“±μ˜ 연산을 ν•΄μ•Όν•©λ‹ˆλ‹€.)

λ”°λΌμ„œ κ·Έλƒ₯ 2차원 배열을 μƒμ„±ν•΄μ„œ visit μ—¬λΆ€λ₯Ό νŒλ‹¨ν•΄μ€¬μŠ΅λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {character[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var solve = function (board) {
  if (!board.length) return board;

  const N = board.length,
    M = board[0].length;
  const visit = new Array(N).fill(null).map((row) => new Array(M).fill(0));

  function bfs(x, y) {
    let surrounded = true;
    const Q = [];
    const pos = [];
    const moves = [
      [0, 1],
      [0, -1],
      [1, 0],
      [-1, 0],
    ];

    visit[x][y] = 1;
    pos.push([x, y]);
    Q.push([x, y]);

    while (Q.length) {
      const [x, y] = Q.shift();

      for (let [dx, dy] of moves) {
        const nx = dx + x,
          ny = dy + y;

        if (nx < 0 || nx >= N || ny < 0 || ny >= M) surrounded = false;
        else {
          if (!visit[nx][ny] && board[nx][ny] === "O") {
            pos.push([nx, ny]);
            Q.push([nx, ny]);
            visit[nx][ny] = 1;
          }
        }
      }
    }

    return [pos, surrounded];
  }

  for (let x = 0; x < board.length; x++) {
    for (let y = 0; y < board[0].length; y++) {
      if (board[x][y] === "O" && !visit[x][y]) {
        const [pos, surrounded] = bfs(x, y);

        if (surrounded) {
          pos.forEach((p) => (board[p[0]][p[1]] = "X"));
        }
      }
    }
  }

  return board;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€