개발/리트코드

[리트코드] 36. Valid Sudoku(유효한 스도쿠)

DOTBAAAM 2025. 6. 16. 19:37
반응형

36. Valid Sudoku(유효한 스도쿠)

문제

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

예제

Input: board =
  [["5","3",".",".","7",".",".",".","."]
  ,["6",".",".","1","9","5",".",".","."]
  ,[".","9","8",".",".",".",".","6","."]
  ,["8",".",".",".","6",".",".",".","3"]
  ,["4",".",".","8",".","3",".",".","1"]
  ,["7",".",".",".","2",".",".",".","6"]
  ,[".","6",".",".",".",".","2","8","."]
  ,[".",".",".","4","1","9",".",".","5"]
  ,[".",".",".",".","8",".",".","7","9"]]
Output: true
Input: board =
  [["8","3",".",".","7",".",".",".","."]
  ,["6",".",".","1","9","5",".",".","."]
  ,[".","9","8",".",".",".",".","6","."]
  ,["8",".",".",".","6",".",".",".","3"]
  ,["4",".",".","8",".","3",".",".","1"]
  ,["7",".",".",".","2",".",".",".","6"]
  ,[".","6",".",".",".",".","2","8","."]
  ,[".",".",".","4","1","9",".",".","5"]
  ,[".",".",".",".","8",".",".","7","9"]]
Output: false

제약 조건

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'.

코드

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function (board) {
  // 중복 체크를 위한 9개의 행, 열, 박스를 각각 Set로 초기화
  const rows = Array.from({ length: 9 }, () => new Set());
  const cols = Array.from({ length: 9 }, () => new Set());
  const boxes = Array.from({ length: 9 }, () => new Set());

  // 행
  for (let i = 0; i < 9; i++) {
    // 열
    for (let j = 0; j < 9; j++) {
      // 현재 칸의 값
      const val = board[i][j];

      // 빈 칸은 중복 검사에서 제외
      if (val === ".") continue;

      // 3x3 박스 인덱스 계산
      const boxIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3);

      // 중복 검사: 이미 해당 행, 열, 박스에 값이 있으면 false 반환
      if (rows[i].has(val) || cols[j].has(val) || boxes[boxIndex].has(val)) {
        return false;
      }

      rows[i].add(val);
      cols[j].add(val);
      boxes[boxIndex].add(val);
    }
  }

  return true;
};

LeetCode - 36. Valid Sudoku

반응형

'개발 > 리트코드' 카테고리의 다른 글

[리트코드] 22. Generate Parentheses  (0) 2025.06.10
[리트코드] 66. Plus One  (0) 2025.06.10