[알고리즘] 스도쿠 검증
2024. 1. 1. 18:21ㆍ알고리즘 풀이/Java
나의 풀이
- 중복 검증은 HashSet의 add 메소드로 할 수 있다.
- 메소드를 분리해서 하는게 심플하다는 것을 느꼈다.
import java.util.Scanner;
import java.util.HashSet;
import java.io.FileInputStream;
class Solution
{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
for(int test_case = 1; test_case <= T; test_case++)
{
int[][] sudoku = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sudoku[i][j] = sc.nextInt();
}
}
System.out.println("#" + test_case + " " + validate_sudoku(sudoku));
}
}
private static int validate_sudoku(int[][] sudoku) {
if (!is_valid_row(sudoku)) {
return 0;
}
if (!is_valid_col(sudoku)) {
return 0;
}
if (!is_valid_square(sudoku)) {
return 0;
}
return 1;
}
private static boolean is_valid_row(int[][] sudoku) {
for (int i = 0; i < 9; i++) {
HashSet<Integer> row = new HashSet<>();
for (int j = 0; j < 9; j++) {
if (!row.add(sudoku[i][j])) {
return false;
}
}
}
return true;
}
private static boolean is_valid_col(int[][] sudoku) {
for (int j = 0; j < 9; j++) {
HashSet<Integer> col = new HashSet<>();
for (int i = 0; i < 9; i++) {
if (!col.add(sudoku[i][j])) {
return false;
}
}
}
return true;
}
private static boolean is_valid_square(int[][] sudoku) {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
HashSet<Integer> square = new HashSet<>();
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
if (!square.add(sudoku[3*y + j][3*x + k])){
return false;
}
}
}
}
}
return true;
}
}
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5Psz16AYEDFAUq
'알고리즘 풀이 > Java' 카테고리의 다른 글
[알고리즘] 창용 마을 무리의 개수 (1) | 2024.01.07 |
---|---|
[알고리즘] 숫자 배열 회전 (0) | 2024.01.01 |
[알고리즘] 두 개의 숫자열 (1) | 2024.01.01 |
[알고리즘] 최빈수 구하기 (0) | 2024.01.01 |
[알고리즘] 파리퇴치3 (1) | 2024.01.01 |