Software Enginner πŸ‡―πŸ‡΅ and πŸ‡°πŸ‡·

Leetcode - Valid Sudoku

Problem Valid Sudoku
Difficulty Medium
Language Java
Time complexity $$O(n ^ 2)$$
Space complexity $$O(n)$$

Problem,

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

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

A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.

Leetcode

Solution,

λ‹€λ₯Έ 방법도 λͺ‡ μžˆλŠ” 것 κ°™λ˜λ° λ‚˜λŠ” λΉ„νŠΈ μ—°μ‚°μœΌλ‘œ ν’€μ—ˆλ‹€. μΆ”κ°€ 곡간을 크게 먹지 μ•ŠλŠ”λ‹€.

ν–‰, μ—΄, λ°•μŠ€λ₯Ό 체크해야 ν•œλ‹€. μ‹œν”„νŠΈ μ—°μ‚°μœΌλ‘œ 각 λΉ„νŠΈμ— ν”Œλž˜κ·Έλ₯Ό κ±Έκ³  ν˜„μž¬ ν–‰/μ—΄/λ°•μŠ€ 와 AND μ—°μ‚°μ‹œ λΉ„νŠΈκ°€ μ‘΄μž¬ν•˜λŠ”κ°€ μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ”κ°€λ‘œ κ²€μ‚¬ν•œλ‹€. μ™œλƒλ©΄, 이미 ν•΄λ‹Ή λΉ„νŠΈ(숫자)κ°€ μžˆλ‹€λ©΄ true 일 ν…Œλ‹ˆ.

class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[] row = new int[9];
        int[] col = new int[9];
        int[] box = new int[9];
        
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] == '.') continue;
                int boxpos = ((i / 3) * 3) + (j / 3);
                int t = 1 << ((int) board[i][j]);
                if ((row[i] & t) > 0 || (col[j] & t) > 0 || (box[boxpos] & t) > 0) {
                    return false;
                }
                row[i] |= t;
                col[j] |= t;
                box[boxpos] |= t;
            }
        }
        
        return true;
    }
}