문제 캡처
소스 코드
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Main {
static Comparator<Integer> comparator(Map<Integer, Integer> map) {
return (key1, key2) -> {
int value1 = map.get(key1), value2 = map.get(key2);
if(value1 == value2) {
return key1 - key2;
}
return value1 - value2;
};
};
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
int r = Integer.parseInt(st.nextToken())-1,
c = Integer.parseInt(st.nextToken())-1,
k = Integer.parseInt(st.nextToken());
int[][] arr = new int[101][101];
for(int i=0;i<3;i++) {
st = new StringTokenizer(bf.readLine());
for(int j=0;j<3;j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
int time = 0;
int rowCnt = 3, colCnt = 3;
while(arr[r][c] != k && time <= 100) {
time++;
if(rowCnt >= colCnt) {
int col = colCnt;
//R연산
for(int i=0;i<rowCnt;i++) {
Map<Integer, Integer> freqMap = new HashMap<>();
//행 연산 실행
for(int j=0;j<colCnt;j++) {
if(arr[i][j] == 0) continue;
freqMap.put(arr[i][j], freqMap.getOrDefault(arr[i][j], 0)+1);
}
TreeMap<Integer, Integer> sortMap = new TreeMap<>(comparator(freqMap));
sortMap.putAll(freqMap);
int nowColCnt = sortMap.size()*2;
for(int j=0;j<nowColCnt;j+=2) {
Entry<Integer, Integer> value = sortMap.pollFirstEntry();
arr[i][j] = value.getKey();
arr[i][j+1] = value.getValue();
}
for(int j=nowColCnt;j<colCnt;j++) {
arr[i][j] = 0;
}
col = Math.max(col, nowColCnt);
}
colCnt = col;
} else {
int row = rowCnt;
//C연산
for(int j=0;j<colCnt;j++) {
Map<Integer, Integer> freqMap = new HashMap<>();
//열 연산 실행
for(int i=0;i<rowCnt;i++) {
if(arr[i][j] == 0) continue;
freqMap.put(arr[i][j], freqMap.getOrDefault(arr[i][j], 0)+1);
}
TreeMap<Integer, Integer> sortMap = new TreeMap<>(comparator(freqMap));
sortMap.putAll(freqMap);
int nowRowCnt = sortMap.size()*2;
for(int i=0;i<nowRowCnt;i+=2) {
Entry<Integer, Integer> value = sortMap.pollFirstEntry();
arr[i][j] = value.getKey();
arr[i+1][j] = value.getValue();
}
for(int i=nowRowCnt;i<rowCnt;i++) {
arr[i][j] = 0;
}
row = Math.max(row, nowRowCnt);
}
rowCnt = row;
}
}
System.out.println(time>100 ? -1 : time);
}
}
'Algorithm' 카테고리의 다른 글
Boj_ 회의실 배정 4 java (0) | 2024.11.11 |
---|---|
[boj] 연구소 3_17142 JAVA (0) | 2024.10.21 |
[boj] Cryptographer’s Conundrum_11269 C++ (0) | 2024.10.14 |
[boj] 양치기꿍_3187 JAVA (1) | 2024.10.07 |
[boj] 좋은수열_2661 JAVA (0) | 2024.09.30 |