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

LeetCode 36 - Valid Sudoku (Medium)

by HandHand 2021. 4. 13.

문제

LeetCode - 36번

풀이 κ³Όμ •

μŠ€λ„μΏ  λ₯Ό κ΅¬ν˜„ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.
λŒ€μ‹  λͺ¨λ“  λ‘œμ§μ„ κ΅¬ν˜„ν•˜λŠ” 것은 μ•„λ‹ˆκ³  μ±„μ›Œμ§„ μˆ«μžλ“€μ— λŒ€ν•΄μ„œ μŠ€λ„μΏ  쑰건을 λ§Œμ‘±ν•˜λŠ”μ§€ νŒλ‹¨ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

λ¨Όμ € 3x3 크기의 μ„œλΈŒ λ°•μŠ€λ“€μ—μ„œ 19 μ‚¬μ΄μ˜ μˆ«μžλ“€ 쀑 쀑볡이 μ‘΄μž¬ν•˜λŠ”μ§€ κ²€μ‚¬ν•©λ‹ˆλ‹€.
이후 각 ν–‰κ³Ό 열을 μˆœνšŒν•˜λ©° λ§ˆμ°¬κ°€μ§€λ‘œ 1
9 μ‚¬μ΄μ˜ 숫자 쀑볡성을 κ²€μ‚¬ν•©λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function (board) {
  const isSubboxRepetition = checkSubboxes(board);
  if (!isSubboxRepetition) {
    return false;
  }

  for (let row = 0; row < 9; row += 1) {
    const cache = [];

    for (let col = 0; col < 9; col += 1) {
      if (board[row][col] === ".") {
        continue;
      }

      if (cache.includes(board[row][col])) {
        return false;
      }

      cache.push(board[row][col]);
    }
  }

  for (let col = 0; col < 9; col += 1) {
    const cache = [];

    for (let row = 0; row < 9; row += 1) {
      if (board[row][col] === ".") {
        continue;
      }

      if (cache.includes(board[row][col])) {
        return false;
      }

      cache.push(board[row][col]);
    }
  }

  return true;
};

function checkSubboxes(board) {
  const hashTable = new Map();

  for (let row = 0; row < 9; row += 1) {
    for (let col = 0; col < 9; col += 1) {
      if (board[row][col] !== ".") {
        const code = encode(row, col);

        if (hashTable.has(code)) {
          const digits = hashTable.get(code);
          if (digits.includes(board[row][col])) {
            return false;
          }

          digits.push(board[row][col]);
          hashTable.set(code, digits);
        } else {
          hashTable.set(code, [board[row][col]]);
        }
      }
    }
  }

  return true;
}

function encode(row, col) {
  return `${~~(row / 3)}${~~(col / 3)}`;
}
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€