조건에 맞게 R, C 연산을 작성하면 된다.
import java.util.*;
//정렬을 위한 클래스 선언
class Operation implements Comparable<Operation>{
int num;
int count;
public Operation(int num, int count) {
this.num = num;
this.count = count;
}
//정렬 기준에 따라 정렬
//개수가 같은 경우 -> 숫자로 오름차순
//개수가 다른 경우 -> 개수로 오름차순
public int compareTo(Operation b){
if(this.count==b.count) return this.num-b.num;
else return this.count-b.count;
}
}
class Arr{
//배열의 크기를 저장할 변수
int r, c;
int[][] arr = new int[101][101];
//초기에 배열의 크기는 3x3이다.
public Arr() {
this.r = 3;
this.c = 3;
}
void R(){
for(int i=1; i<=r; i++){
//HashMap을 이용해 각 숫자의 개수를 counting한다.
HashMap<Integer, Integer> map = new HashMap<>();
for(int j=1; j<=c; j++){
if(arr[i][j]!=0)
map.put(arr[i][j], map.getOrDefault(arr[i][j], 0)+1);
}
//정렬을 위해 list에 옮겨 담는다.
ArrayList<Operation> list = new ArrayList<>();
Iterator<Integer> it = map.keySet().iterator();
while (it.hasNext()){
Integer key = it.next();
list.add(new Operation(key, map.get(key)));
}
//배열의 크기 업데이트
//크기가 100을 초과하지는 못한다.
c = Math.max(c, list.size()*2);
c = Math.min(c, 100);
Collections.sort(list);//정렬
//배열에 연산 결과를 옮겨 담는다.
int currentC = 1;
for (Operation operation : list) {
arr[i][currentC] = operation.num;
arr[i][currentC+1] = operation.count;
currentC+=2;
//처음 100개를 제외한 나머지는 버린다.
if(currentC>99) break;
}
//주의 - 연산 후 크기가 감소할 수 있다.
for(int j=currentC; j<=c; j++){
arr[i][j] = 0;
}
}
}
//R 연산과 동일한 방법으로 진행
void C(){
for(int j=1; j<=c; j++){
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=1; i<=r; i++){
if(arr[i][j]!=0)
map.put(arr[i][j], map.getOrDefault(arr[i][j], 0)+1);
}
ArrayList<Operation> list = new ArrayList<>();
Iterator<Integer> it = map.keySet().iterator();
while (it.hasNext()){
Integer key = it.next();
list.add(new Operation(key, map.get(key)));
}
r = Math.max(r, list.size()*2);
r = Math.min(r, 100);
Collections.sort(list);
int currentR = 1;
for (Operation operation : list) {
arr[currentR][j] = operation.num;
arr[currentR+1][j] = operation.count;
currentR+=2;
if(currentR>99) break;
}
for(int i=currentR; i<=r; i++){
arr[i][j] = 0;
}
}
}
}
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int answer = 0;
int r, c, k;
r = scanner.nextInt();
c = scanner.nextInt();
k = scanner.nextInt();
Arr arr = new Arr();
for(int i=1; i<=3; i++){
for(int j=1; j<=3; j++){
arr.arr[i][j] = scanner.nextInt();
}
}
//A[r][c]가 k가 될때까지 반복
while(arr.arr[r][c]!=k){
//조건에 맞게 R또는 C연산을 수행한다.
if(arr.r>=arr.c) arr.R();
else arr.C();
answer++;
//답이 100을 넘어가면 -1을 출력
if(answer>100){
answer=-1;
break;
}
}
System.out.println(answer);
}
}