[알고리즘] 스도쿠 검증

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

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com