카테고리 없음
[JAVA] 백준 3085번: 사탕 게임 ( 초급 2-2 )
daram
2021. 9. 17. 12:58
문제
상근이는 어렸을 적에 "봄보니 (Bomboni)" 게임을 즐겨했다.
가장 처음에 N×N크기에 사탕을 채워 놓는다. 사탕의 색은 모두 같지 않을 수도 있다. 상근이는 사탕의 색이 다른 인접한 두 칸을 고른다. 그 다음 고른 칸에 들어있는 사탕을 서로 교환한다. 이제, 모두 같은 색으로 이루어져 있는 가장 긴 연속 부분(행 또는 열)을 고른 다음 그 사탕을 모두 먹는다.
사탕이 채워진 상태가 주어졌을 때, 상근이가 먹을 수 있는 사탕의 최대 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 보드의 크기 N이 주어진다. (3 ≤ N ≤ 50)
다음 N개 줄에는 보드에 채워져 있는 사탕의 색상이 주어진다. 빨간색은 C, 파란색은 P, 초록색은 Z, 노란색은 Y로 주어진다.
사탕의 색이 다른 인접한 두 칸이 존재하는 입력만 주어진다.
출력
첫째 줄에 상근이가 먹을 수 있는 사탕의 최대 개수를 출력한다.
import java.util.Arrays;
import java.util.Scanner;
public class baekjoon3085_2 {
private static String[][] info;
private static int n;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
info = new String[n][n];
for (int i = 0; i < n; i++) {
info[i] = sc.nextLine().split("");
}
// 가로 2개의 값을 변경
int max = Math.max(calculateMaxHeight(), calculateMaxRow());
for (int i = 0; i < n; i++) {
for (int j = 1; j < n; j++) {
if (!info[i][j - 1].equals(info[i][j])) {
String tempString = info[i][j];
info[i][j] = info[i][j - 1];
info[i][j - 1] = tempString;
int tempMax = Math.max(calculateMaxHeight(), calculateMaxRow());
if (max < tempMax) {
max = tempMax;
}
info[i][j - 1] = info[i][j];
info[i][j] = tempString;
}
}
}
// 세로 2개의 값을 변경
for (int i = 0; i < n; i++) {
for (int j = 1; j < n; j++) {
if (!info[j - 1][i].equals(info[j][i])) {
String tempString = info[j][i];
info[j][i] = info[j - 1][i];
info[j - 1][i] = tempString;
int tempMax = Math.max(calculateMaxHeight(), calculateMaxRow());
if (max < tempMax) {
max = tempMax;
}
info[j - 1][i] = info[j][i];
info[j][i] = tempString;
}
}
}
System.out.println(max);
}
private static int calculateMaxRow() {
int max = 0;
for (int i = 0; i < n; i++) {
String tempString = info[i][0];
int tempMax = 1;
for (int j = 1; j < n; j++) {
if (info[i][j].equals(tempString)) {
tempMax++;
if (tempMax > max) {
max = tempMax;
}
continue;
}
tempString = info[i][j];
tempMax = 1;
}
}
return max;
}
private static int calculateMaxHeight() {
int max = 0;
for (int i = 0; i < n; i++) {
String tempString = info[0][i];
int tempMax = 1;
for (int j = 1; j < n; j++) {
if (info[j][i].equals(tempString)) {
tempMax++;
if (tempMax > max) {
max = tempMax;
}
continue;
}
tempString = info[j][i];
tempMax = 1;
}
}
return max;
}
}