Leetcode - 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:
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.
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;
}
}