반응형
leetcode.com/problems/valid-sudoku/
문제
Determine if a 9x9 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 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
제한사항
- 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.
- The given board contain only digits 1-9 and the character '.'.
- The given board size is always 9x9.
접근
백트래킹을 이용한 스도쿠 판별!!
코드
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
//주어진 스도쿠가 유효한 스도쿠인지 확인하는 메소드.
}
public static boolean isValidSudoku(char[][] board) {
boolean[] b = new boolean[9];
//룰의 종류, 가로/세로/섭그리드
for(int i=0; i<3; i++) {
//한줄의 규칙
for(int j=0; j<9; j++) {
Arrays.fill(b, false);
for(int k=0; k<9; k++) {
char cur= '.';
if(i == 0) {
//가로
cur=board[j][k];
}else if(i == 1) {
//세로
cur=board[k][j];
}else {
//섭그리드
cur = board[j/3*3 + k/3][j%3*3 + k%3];
}
if(cur=='.') continue;
int val = Character.getNumericValue(cur);
if(b[val-1]) return false;
b[val-1] = true;
}
}
}
return true;
}
}
반응형
'알고리즘 > [ LeetCode ]' 카테고리의 다른 글
[ LeetCode ][JAVA][146] LRU Cache (0) | 2021.05.11 |
---|---|
[ LeetCode ][JAVA][103] Binary Tree Zigzag Level Order Traversal (2) | 2020.10.03 |
[ LeetCode ][JAVA][37] Sudoku Solver (스도쿠 풀기) (0) | 2020.09.24 |
[ LeetCode ][JAVA][169] Majority Element (과반수알고리즘) (2) | 2020.09.24 |
[ LeetCode ][JAVA][31] Next Permutation (다음 순열) (0) | 2020.09.24 |