https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5Psz16AYEDFAUq
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.util.*;
import java.io.*;
public class Solution {
private static int[][] numbers;
public static boolean checkSpace() {
for (int i = 0; i < 27; i += 3) {
int row = (i / 9) * 3;
int column = i % 9;
HashSet<Integer> hs = new HashSet<>();
for (int r = row; r < row + 3; r++) {
for (int c = column; c < column + 3; c++)
hs.add(numbers[r][c]);
}
if (hs.size() != 9)
return false;
}
return true;
}
public static boolean checkLine() {
for (int i = 0; i < 9; i++) {
HashSet<Integer> row = new HashSet<>();
HashSet<Integer> column = new HashSet<>();
for (int j = 0; j < 9; j++) {
row.add(numbers[i][j]);
column.add(numbers[j][i]);
}
if (row.size() != 9 || column.size() != 9)
return false;
}
return true;
}
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int T = Integer.parseInt(st.nextToken());
for (int t = 1; t <= T; t++) {
numbers = new int[9][9];
for (int i = 0; i < 9; i++) {
st = new StringTokenizer(br.readLine(), " ");
for (int j = 0; j < 9; j++)
numbers[i][j] = Integer.parseInt(st.nextToken());
}
System.out.print("#" + t + " ");
if (checkSpace() && checkLine())
System.out.println(1);
else
System.out.println(0);
}
}
}
행과 열을 한 줄 씩 검사하는 checkLine( ) 메소드와 한 칸(3x3) 씩 검사하는 메소드를 구현하였습니다.
checkLine( )과 checkSpace( )가 모두 true를 반환할 경우 결과값 1을 출력하게 하였습니다.
두 메소드 모두 HashSet을 이용하여 1부터 9까지 중복없이 들어올 경우,
HashSet의 크기가 9라는 점을 이용하여
중복된 숫자가 들어온 경우라면 크기가 9가 아니므로 false를, 중복없이 들어온 경우라면 크기가 9이므로 true를 반환하게 하였습니다.
약간 까다로울 수 있는 부분은
checkSpace( ) 메소드에서 인덱스를 설정하는 부분인 것 같습니다.
row는 0, 3, 6 순으로 증가해야 하고,
column 또한 row의 각 값에서 0, 3, 6 순으로 증가해야 하므로
i 자체를 3, 6, 9, 12, 15, ...로 증가하게 해서
9로 나눴을때의 몫은 row로, 나머지는 column으로 대입시켰습니다.
'Algorithm > 백준+프로그래머스+SWEA+정올+구름' 카테고리의 다른 글
[Algorithm] 백준 2961 도영이가 만든 맛있는 음식 (0) | 2021.08.12 |
---|---|
[Algorithm] 백준 3040 백설공주와 일곱난쟁이 (0) | 2021.08.12 |
[Algorithm] 백준 16926 배열 돌리기1 (0) | 2021.08.11 |
[Algorithm] 백준 1158 요세푸스 문제 (0) | 2021.08.10 |
[Algorithm] 백준 1427 소트인사이드 (0) | 2021.08.10 |