728x90
반응형
문제
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.
내 생각
가로, 세로, 사각형을 따로 구분해서 중복된 숫자가 존재하지 않는지 판단하는 문제이다. 즉, 유효한 스도쿠인지 판단하는 문제!
조건은 아래 3개를 판단해야 한다.
1. 가로방향 1~9가 중복되었는지
2. 세로방향 1~9가 중복되었는지
3. 3*3 영역에서 1~9가 중복되었는지
이거 for문으로 노가다 구현을 해야하나 ㅠ 했는데 HashSet을 이용해보기로!
* HashSet
중복을 허용하지 않는 컬렉션으로 동일한 요소를 중복해서 저장할 수 없다.
add() 메서드를 사용하여 새로운 요소를 추가할 때 이미 HashSet에 존재하는 요소라면 추가되지 않고 false를 반환한다. (각 숫자가 한 번씩만 나타나는지를 확인할 수 있)
내 코드
class Solution {
public boolean isValidSudoku(char[][] board) {
// 각 위치 정보를 저장하기 위한 HashSet
Set<String> set = new HashSet<>();
// 보드의 각 칸을 순회하면서 체크
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
char num = board[i][j];
// 현재 칸이 비어있지 않을 경우에만
if (num != '.') {
// 각 행, 열, 3x3 블록에 중복된 숫자가 있는지 확인
// 만약 중복된 숫자가 있으면 false
if (!set.add(num + "row:" + i) || !set.add(num + "col:" + j) || !set.add(num + "block:" + i/3 + "-" + j/3)) {
return false;
}
}
}
}
// 중복된 숫자가 없으면 true
return true;
}
}
728x90
반응형
'Algorithm > 코딩테스트 (Java)' 카테고리의 다른 글
[LeetCode] 24. Swap Nodes in Pairs (0) | 2024.05.21 |
---|---|
[LeetCode] 300. Longest Increasing Subsequence (0) | 2024.05.20 |
[LeetCode] 79. Word Search (0) | 2024.05.08 |
[JUNGOL/정올][재귀] 자가진단 1 (0) | 2023.09.21 |
[JUNGOL/정올][재귀] 연습문제 1 (0) | 2023.09.21 |
댓글