Valid Sudoku
2024. 10. 4. 09:54ㆍ알고리즘/Leetcode
반응형
Solution
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.
Example

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
Explanation
class Solution {
public boolean isValidSudoku(char[][] board) {
Set seen = new HashSet();
for (int i=0; i<9; ++i) {
for (int j=0; j<9; ++j) {
char number = board[i][j];
if (number != '.')
if (!seen.add(number + " in row " + i) ||
!seen.add(number + " in column " + j) ||
!seen.add(number + " in block " + i/3 + "-" + j/3))
return false;
}
}
return true;
}
}
To solve this problem, firstly we need to know what Set is and how to use it. Set cannot contain duplicate numbers and stores only a unique value. With this feature, we don't need to create multiple nested for loops and values with their location are stored.
Nested for loops are created and if the value is not '.', check it can be added in seen, the set. If it is already contained in a row, a column, or a block, it immdiately returns false. Otherwise, it returns true.
반응형
'알고리즘 > Leetcode' 카테고리의 다른 글
| Reverse Integer (0) | 2024.10.07 |
|---|---|
| Reverse String (0) | 2024.10.06 |
| Two Sum (1) | 2024.09.24 |
| Move Zeroes (2) | 2024.09.23 |
| Plus One (2) | 2024.09.20 |