본문 바로가기

CodingTEST

[SW Expert D2] 1974. 스도쿠 검증

반응형

1974. 스도쿠 검증 

 

SW Expert Academy

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

swexpertacademy.com

 

 

문제 분석

 

  • 9 x 9 스도쿠를 입력 받아서 스도쿠가 성립하면 1, 아니면 0 출력해라
    • 스도쿠 성립 조건 
      1. 가로줄 1~9 하나씩
      2. 세로줄 1~9 하나씩
      3. 3 x 3 범위 1~9 하나씩

 

해결 포인트

 

  • 3 x 3 범위를 확인할 이차원 배열 ArrayList 필요 : ArrayList<Integer> [][] part = new ArrayList [3][3];
    • 세로 3번 나눠지고 가로 3번 나눠지니까 ArrayList [3][3] 로 구현
    • 가로 세로 값을 1,2,3 | 4,5,6 | 7,8,9 로 3묶음으로 나눠야 한다. 
      어떻게? part[(i-1)/3][(j-1)/3].add(nums[i][j]); 식으로 
  • 가로 세로 확인은 이차원 for문으로 확인할 때 내부 for문 끝나고 확인
    • 입력받은 숫자(이차원 배열)을 가로는 num[i][j] 세로는 num[j][i]
  •  중복된 숫자가 들어있는지 체크는 stream().distinct() 했는 때 size가 9개인지 확인
    • width.stream().distinct().count() != 9 경우 스도쿠 성립되지 않음

 

코드

 

import java.util.*;
import java.util.stream.Stream;
import java.io.*;

class Solution
{
	public static void main(String args[]) throws Exception
	{

		//System.setIn(new FileInputStream("res/input.txt"));


		Scanner sc = new Scanner(System.in);
		int T;
		T=sc.nextInt();

		for(int test_case = 1; test_case <= T; test_case++)
		{
			int isCheck = 1;
			
			int [][] nums = new int[10][10];

			for (int i = 1; i <= 9; i++) {
				for (int j = 1; j <= 9; j++) {
					nums[i][j] = sc.nextInt();
				}
			}

			ArrayList<Integer> [][] part = new ArrayList [3][3];
			for (int i = 0; i < 3; i++) {
				for (int j = 0; j < 3; j++) {
					part[i][j] = new ArrayList<>(); 
				}
			}
			
			for (int i = 1; i <= 9; i++) {
				ArrayList<Integer> width = new ArrayList<>();
				ArrayList<Integer> height = new ArrayList<>();
				for (int j = 1; j <= 9; j++) {
					part[(i-1)/3][(j-1)/3].add(nums[i][j]);
					width.add(nums[i][j]);
					height.add(nums[j][i]);
				}
				
				// 가로 세로 확인
				if(width.stream().distinct().count() != 9 ||
						height.stream().distinct().count() != 9) {
					isCheck = 0;
					break;
				}
			}
			
			// 3 x 3  부분 확인
			for (int i = 0; i < 3; i++) {
				for (int j = 0; j < 3; j++) {
					if(part[i][j].stream().distinct().count() != 9) {
						isCheck = 0;
						break;
					}
				}
			}
			
			System.out.println("#" + test_case  + " " + isCheck);
			
		}
	}
}
반응형