문제

* 해당 문제의 모든 저작권은 SWEA 측에 있으며 본 블로그는 SWEA  약관을 위배하지 않음을 명시합니다.*

 

ttps://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5Pq-OKAVYDFAUq 

 

SW Expert Academy

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

swexpertacademy.com


풀이

첫번째 루프 - 반복문 사용 최소화를 위해 묶음

1. 9개의 행 체크. 1~9가 있는지.

2. 9개의 열 체크. 1~9가 있는지.

 

두번째 루프 - 메소드 분리하면 보기 편할듯

1. 3*3 박스 체크. 1~9가 있는지.

 

하나라도 1~9가 없다면 정답을 0으로 변경 및 루프 탈출


소스 코드

import java.util.Scanner;
 
public class Solution {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
 
        int T = sc.nextInt();
 
        for (int test_case = 1; test_case <= T; test_case++) {
            int answer = 1;
             
            int[][] arr = new int[9][9];
             
            // input
            for(int i = 0; i < 9; i++) {
                for(int j = 0; j < 9; j++) {
                    arr[i][j] = sc.nextInt();
                }
            }
             
            //row, col check
            for(int i = 0; i < 9; i++) {
                 
                int[] rcheck = {0, 0, 0, 0, 0, 0, 0, 0, 0};
                int[] ccheck = {0, 0, 0, 0, 0, 0, 0, 0, 0};
                int r = 0, c = 0;
                 
                for(int j = 0; j < 9; j++) {
                    rcheck[arr[i][j] - 1] = 1;
                    ccheck[arr[j][i] - 1] = 1;
                }
                 
                for(int k = 0; k < 9; k++) {
                    r += rcheck[k];
                    c += ccheck[k];
                }
                 
                if (r != 9 || c != 9) {
                    answer = 0;
                    break;
                }
            }
             
            // 3*3 Divide and conquer
            for (int i = 0; i < 9; i += 3) {             
                for (int j = 0; j < 9; j += 3) {
                     
                    int[] bcheck = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                    int b = 0;
                     
                    for (int x = i; x < i+3; x++) {
                        for (int y = j; y < j+3; y++) {
                            bcheck[arr[x][y] - 1] = 1;
                        }
                    }
                     
                    for(int k = 0; k < 9; k++) {
                        b += bcheck[k];
                    }
                     
                    if (b != 9) {
                        answer = 0;
                        break;
                    }
                }
            }
             
             
            System.out.println("#" + test_case + " " + answer);
        }
    }
}

+ Recent posts