import java.io.*;
public class Main {
public static boolean same(int[][] a, int x, int y, int n) {
for (int i=x; i<x+n; i++) {
for (int j=y; j<y+n; j++) {
if (a[x][y] != a[i][j]) {
return false;
}
}
}
return true;
}
public static void solve(int[][] a, int[] cnt, int x, int y, int n) {
if (same(a, x, y, n)) {
cnt[a[x][y]+1] += 1;
return;
}
int m = n/3;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
solve(a, cnt, x+i*m, y+j*m, m);
}
}
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(br.readLine());
int[][] a = new int[n][n];
int[] cnt = new int[3];
for (int i=0; i<n; i++) {
String[] line = br.readLine().split(" ");
for (int j=0; j<n; j++) {
a[i][j] = Integer.valueOf(line[j]);
}
}
solve(a, cnt, 0, 0, n);
for (int i=0; i<3; i++) {
System.out.println(cnt[i]);
}
}
}
(x, y)부터 가로로 n개, 세로로 n개의 종이 개수를 확인하는 함수인 solve() 재귀호출하여 해결한다. 부분 문제를 호출하기 전에 같은 수로 되어있는지를 확인해보고 그렇지 않으면 부분 문제를 호출하도록 구현한다.
import java.util.HashMap;
import java.util.HashSet;
public class DifferentFrequency {
public static int solution(String s) {
int answer = 0;
HashMap<Character, Integer> sh = new HashMap<>();
HashSet<Integer> ch = new HashSet<>();
for(char x : s.toCharArray()) {
sh.put(x, sh.getOrDefault(x, 0) + 1);
}
for(char key : sh.keySet()) {
while(ch.contains(sh.get(key))) {
answer++;
sh.put(key, sh.get(key) - 1);
}
if(sh.get(key) == 0) {
continue;
}
ch.add(sh.get(key));
}
return answer;
}
public static void main(String[] args) {
System.out.println(DifferentFrequency.solution("aebbbbc"));
}
}
정말 좋은 글 감사합니다!